Shell loop calling sed command every iteration

时间:2016-07-11 22:33:13

标签: bash shell sed

I want to use sed to get rid of a bunch of instances of things in a file If say I have a file called found that has

,cat
,dog
,rat

And I have a file data that is like

1,dog,bird,cat,rat
2,cat,dog
3,bernie,cat,rat

By running this command I want to get a file(That I call NotFound) like

1,bird,
2
3,bernie

Right now I'm thining I could do it in some sort of way like below, but I know this isn't right

while read p; do
        cat data | sed "s/$p//g" > NotFound
done < found

2 个答案:

答案 0 :(得分:1)

在shell中循环是一种低效的方法。我建议像:

sed 's/^/s|/;s/$/||g/' found | sed -f - data > notfound

换句话说,将模式转换为单个sed程序并对数据文件运行。

答案 1 :(得分:0)

Inline editing of sed will come handy here as you will keep modifying same file for each line in found file:

while read -r p; do 
    sed -i "s/$p//g" data
done < found

# check output

cat data
1,bird
2
3,bernie