Search code examples
bashawkcut

bash: How to modify a string within a field


I have the following lines:

field1    1-23_4_5    field3
field1    2-40_5_7    field3
field1    3-43_7_9    field3
             .
             .
             .  

I would like to modify the second field so that

1-23_4_5 becomes 1-23

I am thinking the combination of awk and cut would do the trick. Is there a simple way to go about this?

Thank you so much for your help in advance.


Solution

  • Through awk,

    $ awk 'sub(/_[^_]*_[^_]*$/,"",$2)1' file
    field1 1-23 field3
    field1 2-40 field3
    field1 3-43 field3
    

    Through sed,

    $ sed 's/^\([^ ]\+\ *[^_]\+\)[^ ]\+/\1/g' file
    field1    1-23    field3
    field1    2-40    field3
    field1    3-43    field3