带有'for'循环的多个'sed'命令

use*_*159 1 bash for-loop sed

我想在几个文档中替换几个字符串.我知道如何sed使用该-e选项组合命令,但我不知道如何在脚本中将它们组合在一起运行多个文件.

我尝试使用'for'循环,但它不起作用.

for i in `ls *.txt`; do sed -e 's/22/twenty two/g' \ -e 's/23/twenty three/g'$i > new/$i; done
Run Code Online (Sandbox Code Playgroud)

任何想法如何用做到这一点shell,awk,PythonPerl

fed*_*qui 6

你在做:

for i in `ls *.txt`
do
   sed -e 's/22/twenty two/g' \ -e 's/23/twenty three/g'$i > new/$i
                              ^                       ^^^
                              why is this here?       missing space!
done
Run Code Online (Sandbox Code Playgroud)

哪些可以改写为:

for i in *.txt  # <-- no need to `ls`!!
do
   sed -e 's/22/twenty two/g' -e 's/23/twenty three/g' "$i" > new/"$i"
done
Run Code Online (Sandbox Code Playgroud)

所以你的问题是:

  • \在命令之间奇怪.
  • 缺少sed 's...'文件名之间的空格.

并提出一个建议:

  • 不要使用ls,只需展开*.txt.

  • 这也应该有效:`sed's/22 /二十二/ g; s/23 /二十三/ g' (3认同)

小智 6

如果你使用awk,你不需要循环

awk '{gsub(/22/,"twenty two");gsub(/23/,"twenty three");print > "new/"FILENAME}' *.txt
Run Code Online (Sandbox Code Playgroud)