IslandPatrol IslandPatrol - 2 months ago 7
Linux Question

How to replace a string in a file only if the line containing it also contains a number found in another file using Bash?

I would like to replace all instances of

target
with
replace
in the following file.csv using Bash, but only if the line containing it also contains a number found in list.txt:

file.csv:

1,abc,target,abc
2,abc,target,abc
3,abc,target,abc


list.txt:

1
3


Desired output:

1,abc,replace,abc
2,abc,target,abc
3,abc,replace,abc


I am attempting to use
sed
:

sed 's/target/replace' file.csv > newfile.csv


How can I include logic to check each line against list.txt?

Answer

It is a job suited more for awk:

awk 'BEGIN { FS=OFS="," }       # set input/output field delimiter to comma
   FNR == NR {                  # for 1st file in the arguments i.e. list.txt
      a[$1]                     # store each value of $1 in an array a
      next                      # move to next record
}
$1 in a {                       # for 1st file in the arguments i.e. file.csv
   sub(/target/, "replace", $3) # replace target by replace in 3rd column
} 1' list.txt file.csv          # print each record from 2nd file

1,abc,replace,abc
2,abc,target,abc
3,abc,replace,abc

Code Demo