I know similar questions have been asked, but I am a novice, having just picked up Linux the last few months, and the particulars of my question have made me unable to adapt other solutions to my problem.

I wish to replace different strings in a single line with specific matched strings indicated in a CSV.

An example: file1:


file2.csv (two column csv):

1[&label, "1[&tag=2,label"
2[&label, "2[&tag=5,label"
3[&label, "3[&tag=3,label"

I would like to replace 1[&label with 1[&tag=2,label (etc...) in the single line file, such that I would end up with:


Note that the csv does not contain any entries for [&label entries without an individual tag (the 1[&label ), but I still need those [&label entries in the final output file.


Here's one way to do it, using Bash:


# read the line to act upon
line=$(head -n 1 $1)

while read substitution
    # get the first field, delimited by a comma
    findvar=`echo $substitution | cut -d, -f1`
    # remove the quotes and get the second field, delimited by a space
    replacevar=`echo $substitution | sed 's/"//g' | cut -d' ' -f2`
    # replace all occurrences of the find variable with the replacement
done < $2

echo $line

If this script is named


then you could call

sh substitute.sh file1 file2.csv

This is making several assumptions:

  • Your CSV is in the format you describe. In your example, values in the first column are not quoted, but values in the second column are. Additionally, the example includes a space after the delimiter. You would need to adjust the script if the actual CSV format differs.
  • Since substitutions from the CSV are processed one at a time, it is possible that a later substitution will match a substitution made previously. This may not be your intention.

For example, if your input line is

foo bar baz

And your CSV file with substitutions is

foo, "bar"
bar, "baz"

You might intend the result to be

bar baz baz

But the result would be

baz baz baz
  • Worked great and your details and comments have allowed me to make minor edits and apply the script to a variety of other find-and-replace tasks. Thanks! – mav1234 Jan 11 '17 at 15:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.