0

I have a file called foo.file. In it are many things. I wanted to get rid of two lines containing these keywords. employee.csv and instrument.csv. The sed -I flag is powerful feature in sed command. I like it to use on edit files in place.

It works just fine when I use in in command line format

 sed -i '/employee.csv/d' foo.file

but when I try to loop the keywords. It does not work.

 for i in employee.csv instrument.csv ;
 do
 sed -i '/"$i"/d' foo.file ;
 done

~

capser
  • 2,442
  • 5
  • 42
  • 74
  • 4
    See: [Difference between single and double quotes in bash](http://stackoverflow.com/q/6697753/3776858) – Cyrus Sep 22 '17 at 22:14
  • 2
    A different approach: `sed -i '/employee.csv/d;/instrument.csv/d' foo.file` or shorter: `sed -i '/employee.csv\|instrument.csv/d' foo.file` – Cyrus Sep 22 '17 at 22:17
  • So there is no variable interpretation between bullet quotes - even in sed. Hmmmmm. that is not fun. – capser Sep 22 '17 at 22:28
  • 2
    Use `"/$i/d"` or `'/'"$i"'/d'`. – Cyrus Sep 22 '17 at 22:36
  • 3
    Understand the interaction between the shell which interprets (or not) the strings inside quotes, removing the quotes, and `sed` which processes what the shell gives it. In the code in the question, the value in the second argument to `sed` is `/"$i"/d` where the double quotes are retained but the single quotes are removed. It's useful, even important, to understand what the shell sees as the text of command lines and what the programs it executes see as command line arguments. – Jonathan Leffler Sep 22 '17 at 23:13

2 Answers2

3
for i in "employee.csv" "instrument.csv"; do
    sed -i '/'"$i"'/d' foo.file;
done

You can also use regular expressions with sed:

sed -ri '/(employee|instrument).csv/d' foo.file;
Rowshi
  • 360
  • 2
  • 11
2

Using sed to make an in-place substitution change:

for i in employee.csv instrument.csv; do
    do sed -i "s/$i//g" foo.file;
done
rahuL
  • 3,330
  • 11
  • 54
  • 79