Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

bash - How to use the name of the file with sed in a find expression

Trying to answer Using Bash/Perl to modify files based on each file's name I ended in a point in which I don't know how to use find and sed all together.

Let's say there is a certain structure of files in which we want to change a line, appending the name of the file.

If it was a normal for loop we would do:

for file in dir/*
do
   sed -i "s/text/text plus $file/g" $file
done

But let's say we want to use find to change files from all subdirectories. In this case, I would use...

find . -type f -exec sed -i "s/text/text plus {}/g" {} ;
                                              ^
                                   it does not like this part

but these {} within sed are not accepted and I get the error

sed: -e expression #1, char 20: unknown option to `s'

I found some similar questions (1) but could not generalize it enough to make it understandable for me in this case.

I am sure you guys will come with a great solution for this. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I really think the issue is that your files name contains a / that is why sed believes it start the options strings.

Replace / by @ in you sed command would do the job.

I try that on Linux BASH and it work perfectly

find . -type f -exec sed -i -e "s@text@test plus {}@g" {} ;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...