Single sed command for multiple substitutions?

女生的网名这么多〃 提交于 2019-12-11 04:09:26

问题


I use sed to substitute text in files. I want to give sed a file which contains all the strings to be searched and replaced in a given file.

It goes over .h and .cpp files. In each file it searches for file names which are included in it. If found, it substitutes for example "a.h" with "<a.h>" (without the quotes).

The script is this:

For /F %%y in (all.txt) do 
   for /F %%x in (allFilesWithH.txt) do
       sed -i s/\"%%x\"/"\<"%%x"\>"/ %%y
  • all.txt - List of files to do the substitution in them
  • allFilesWithH.txt - All the include names to be searched

I don't want to run sed several times (as the number of files names in input.txt.) but I want to run a single sed command and pass it input.txt as input.

How can I do it?

P.S I run sed from VxWorks Development shell, so it doesn't have all the commands that the Linux version does.


回答1:


sed itself has no capability to read filenames from a file. I'm not familiar with the VxWorks shell, and I imagine this is something to do with the lack of answers... So here are some things that would work in bash - maybe VxWorks will support one of these things.

sed -i 's/.../...' `cat all.txt`

sed -i 's/.../...' $(cat all.txt)

cat all.txt | xargs sed -i 's/.../...'

And really, it's no big deal to invoke sed several times if it gets the job done:

cat all.txt | while read file; do sed -i 's/.../.../' $file; done

for file in $(cat all.txt); do   # or `cat all.txt`
    sed -i 's/.../.../' $file
done



回答2:


You can eliminate one of the loops so sed only needs to be called once per file. Use the -f option to specify more than one substitution:

For /F %%y in (all.txt) do 
    sed -i -f allFilesWithHAsSedScript.sed %%y

allFilesWithHAsSedScript.sed derives from allFilesWithH.txt and would contain:

s/\"file1\"/"\<"file1"\>"/
s/\"file2\"/"\<"file2"\>"/
s/\"file3\"/"\<"file3"\>"/
s/\"file4\"/"\<"file4"\>"/

(In the article Common threads: Sed by example, Part 3 there are many examples of sed scripts with explanations.)

Don't get confuSed (pun intended).




回答3:


What I'd do is change allFilesWithH.txt into a sed command using sed.

(When forced to use sed. I'd actually use Perl instead, it can also do the search for *.h files.)



来源:https://stackoverflow.com/questions/1519948/single-sed-command-for-multiple-substitutions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!