How to replace a particular field in a file based on the content of another field?

5,777

Anchor it (^ is start of line) so that the A is only matched if it's the first character:

$ letter=A; id=MYNEWIDSTRING; sed "/^$letter /s/[^ ]*/$id/2" file
A MYNEWIDSTRING EXTERNAL
B CC32480A3247F84A SYSTEM
C EC2A63F12A63B76C EXTERNAL

by the way, if you want to pass variables to sed but you need strong quoting remember you can turn quoting on and off while adding double quotes for the variables - ugly but probably best practice in general:

sed '/^'"$letter"' /s/[^ ]*/'"$id"'/2'
Share:
5,777

Related videos on Youtube

Arronical
Author by

Arronical

Always learning, normally trying not to offend.

Updated on September 18, 2022

Comments

  • Arronical
    Arronical over 1 year

    I have a file with the following format:

    A 485C72F95C72E15C EXTERNAL
    B CC32480A3247F84A SYSTEM
    C EC2A63F12A63B76C EXTERNAL
    

    I want to supply the letter in the first column using the value of the variable 'letter', and replace the value in the second column with a value I supply in the variable 'id'. The third column may or may not differ or match in any case. The first and second columns will never contain spaces or special characters.

    I've tried to use sed, but my sed-fu is not strong. I came up with this:

    letter=A
    id=MYNEWIDSTRING
    sed "/$letter /s/[^ ]*/$id/2"
    

    The output is:

    A MYNEWIDSTRING EXTERNAL
    B MYNEWIDSTRING SYSTEM
    C EC2A63F12A63B76C EXTERNAL
    

    The id is replaced in two lines, I'm assuming this is due to 'A ' being matched at the end of the original id string.

    I know to use sed -i to edit the file inplace, but not doing it yet, as my command is still a bit dodgy.

    Where have I gone wrong, or should I be using a different method?

  • Arronical
    Arronical over 7 years
    Oh what an anchor I am! So simple! I was almost there!
  • Zanna
    Zanna over 7 years
    ^_^ thanks for kindly not quite getting there and thus giving me an excuse to play with sed
  • Arronical
    Arronical over 7 years
    The quoting stuff is very useful too, I always feel worried about unquoted variables!
  • Zanna
    Zanna over 7 years
    me too haha I'm sure I err on the side of overquoting