Search code examples
bashawksedcut

How to shorted the middle field of text without losing the other fields


Sorry if this has already been covered. I failed to find anything that fit.

If I have a text file with fields of variable length, how can I truncate one field without sacrificing the other fields? An example;

firstField secondfieldisthislong thirdField
firstField secondfieldisreallylongandgoesonforever thirdField
firstField secondshortfield thirdField

I'd like to truncate the second field to a fixed length. Cut doesn't seem to be able to do this, and my awk/sed skill aren't great. Thanks.


Solution

  • With awk:

    awk '{$2 = substr($2, 1, 10)}; 1' file.txt
    

    replace 10 with the length of characters you want.

    here we are rebuilding the record(s) with the second field truncated to desired length.

    substr($2, offset, length) will do string slicing, starting from offset upto length characters.

    Example:

    % cat file.txt                              
    firstField secondfieldisthislong thirdField
    firstField secondfieldisreallylongandgoesonforever thirdField
    firstField secondshortfield thirdField
    
    % awk '{$2 = substr($2, 1, 6)}; 1' file.txt
    firstField second thirdField
    firstField second thirdField
    firstField second thirdField
    
    % awk '{$2 = substr($2, 1, 10)}; 1' file.txt
    firstField secondfiel thirdField
    firstField secondfiel thirdField
    firstField secondshor thirdField