Search code examples
regexstringsedcut

How to trim trailing characters (not whitespace) from a string?


How could you go about trimming an n number of characters from the end of a string?

Strings of interest in column 2:

1 022102201212021
2 201212210221021
3 021201122012210
4 201212101120002

Trimmed strings with last 5 characters removed:

1 0221022012
2 2012122102
3 0212011220
4 2012121011

Would like to be able to trim any arbitrary number of characters off of the end of the string in column 2. Thanks.


Solution

  • If the column to trim is the last column:

    awk '{print substr($0, 0, length-5)}' < INPUT > OUTPUT
    

    If there might be more columns after the column to trim:

    awk '{$2 = substr($2, 0, length($2)-5); print}' < INPUT > OUTPUT