编写一个 shell 脚本来替换多个文件中的多个字符串

Write a shell script that replaces multiple strings in multiple files

我需要在目录中的许多文件中搜索关键字列表并为所有这些文件添加前缀。例如,如果我目录中的各种文件包含术语 foobarbaz,我需要将这些术语的所有实例更改为:prefix_fooprefix_barprefix_baz.

我想写一个 shell 脚本来执行此操作,这样我就可以避免在 SublimeText 中一次搜索一个关键字(有很多)。不幸的是,我的 shell-fu 没有那么强。

到目前为止,按照 this 建议,我创建了一个名为 "replace.sed" 的文件,其中所有术语的格式如下:

s/foo/prefix_foo/g
s/bar/prefix_bar/g
s/baz/prefix_baz/g

它建议与此列表一起使用的终端命令是:

sed -f replace.sed < old.txt > new.txt

我能够通过设置以下脚本来修改它以替换文件中的实例(而不是创建新文件),我称之为 inline.sh:

#!/bin/sh -e
in=${1?No input file specified}
mv $in ${bak=.$in.bak}
shift
"$@" < $bak > $in

综合起来,我得到了这个命令:

~/inline.sh old.txt sed -f replace.sed

我尝试了这个并且它有效,一次一个文件。我如何调整它以搜索和替换整个目录中的所有文件?

在脚本中:

#!/bin/bash
files=`ls -1 your_directory | egrep keyword`

for i in ${files[@]}; do
    cp ${i} prefix_${i}
done

当然,这会将原件留在原处。

for f in *; do
  [[ -f "$f" ]] && ~/inline.sh "$f" sed -f ~/replace.sed
done