Friday, April 26, 2024
5
rated 0 times [  5] [ 0]  / answers: 1 / hits: 6189  / 2 Years ago, sat, july 2, 2022, 1:31:59

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?


More From » command-line

 Answers
3

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'

[#13156] Monday, July 4, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
oileweaty

Total Points: 337
Total Questions: 108
Total Answers: 105

Location: Western Sahara
Member since Mon, May 3, 2021
3 Years ago
;