how to truncate lines in a text file

Discussion in 'Site & Server Administration' started by lanmonkey, Sep 19, 2007.

  1. #1
    I have a text file and I would like to truncate every line down to about 16 characters....

    Anyone know how to do this on linux?

    thanks
     
    lanmonkey, Sep 19, 2007 IP
  2. rederick

    rederick Peon

    Messages:
    128
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You could use a PHP script. Something like this - if you wanted to write the out put to a file - that could be done with file_put_contents.


    
    <?php
    
    $file = file_get_contents("comma.txt");
    $file = explode("\n",$file);
    
    foreach ($file as $line){
    
    	$first_sixteen .=  substr($line,0,16) ."\n";
    
    }
    
    echo $first_sixteen;
    
    ?>
    
    PHP:
     
    rederick, Sep 19, 2007 IP
  3. sysadm

    sysadm Peon

    Messages:
    20
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    PHP? I could replace your script with a few chars... and I could problably replace you with a very short shell script, just joking :^)

    You can use sed or awk, which would be very simple, but in this case make use of cut (or even tr).
    cut (1) - remove sections from each line of files
    tr (1) - translate or delete characters

    Just read the manual for cut...
     
    sysadm, Sep 20, 2007 IP
  4. lanmonkey

    lanmonkey Active Member

    Messages:
    549
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    60
    #4
    Thanks guys

    thats php script is very useful, especially for someone withour shell access

    I found the answer:

    cut -c1-16 /path/to/filename > /path/to/output_filename
     
    lanmonkey, Sep 21, 2007 IP