command line - How to replace a particular field in a file based on the content of another field? - Ask Ubuntu


i have file following format:

a 485c72f95c72e15c external b cc32480a3247f84a system c ec2a63f12a63b76c external 

i want supply letter in first column using value of variable 'letter', , replace value in second column value supply in variable 'id'. third column may or may not differ or match in case. first , second columns never contain spaces or special characters.

i've tried use sed, sed-fu not strong. came this:

letter=a id=mynewidstring sed "/$letter /s/[^ ]*/$id/2" 

the output is:

a mynewidstring external b mynewidstring system c ec2a63f12a63b76c external 

the id replaced in 2 lines, i'm assuming due 'a ' being matched @ end of original id string.

i know use sed -i edit file inplace, not doing yet, command still bit dodgy.

where have gone wrong, or should using different method?

anchor (^ start of line) a matched if it's first character:

$ letter=a; id=mynewidstring; sed "/^$letter /s/[^ ]*/$id/2" file mynewidstring external b cc32480a3247f84a system c ec2a63f12a63b76c external 

by way, if want pass variables sed need strong quoting remember can turn quoting on , off while adding double quotes variables - ugly best practice in general:

sed '/^'"$letter"' /s/[^ ]*/'"$id"'/2' 

Comments

Popular posts from this blog

download - Firefox cannot save files (most of the time), how to solve? - Super User

windows - "-2146893807 NTE_NOT_FOUND" when repair certificate store - Super User