我需要对文件夹(及其子文件夹)中的所有文件执行正则表达式查找和替换。要做到这一点,linux shell命令是什么?
例如,我想对所有文件运行此命令,并用新的替换文本覆盖旧文件。
sed 's/old text/new text/g'
发布于 2015-01-21 22:58:16
我更喜欢使用find | xargs cmd
而不是find -exec
,因为它更容易记忆。
此示例将当前目录或其下的.txt文件中的"foo“全局替换为"bar”:
find . -type f -name "*.txt" -print0 | xargs -0 sed -i "s/foo/bar/g"
如果您的文件名不包含空格等时髦字符,则可以省略-print0
和-0
选项。
发布于 2009-05-25 03:12:44
在可移植性方面,我不依赖特定于linux或BSD的sed特性。取而代之的是,我使用了Kernighan和Pike的“Unix编程环境”一书中的overwrite
脚本。
然后,命令为
find /the/folder -type f -exec overwrite '{}' sed 's/old/new/g' {} ';'
overwrite
脚本(我到处都在使用它)是
#!/bin/sh
# overwrite: copy standard input to output after EOF
# (final version)
# set -x
case $# in
0|1) echo 'Usage: overwrite file cmd [args]' 1>&2; exit 2
esac
file=$1; shift
new=/tmp/$$.new; old=/tmp/$$.old
trap 'rm -f $new; exit 1' 1 2 15 # clean up files
if "$@" >$new # collect input
then
cp $file $old # save original file
trap 'trap "" 1 2 15; cp $old $file # ignore signals
rm -f $new $old; exit 1' 1 2 15 # during restore
cp $new $file
else
echo "overwrite: $1 failed, $file unchanged" 1>&2
exit 1
fi
rm -f $new $old
其思想是,只有当命令成功时,它才覆盖文件。在find
中很有用,也适用于您不想使用的地方
sed 's/old/new/g' file > file # THIS CODE DOES NOT WORK
因为外壳程序会在sed
读取文件之前将其截断。
发布于 2009-05-25 02:50:58
我可以建议(在备份您的文件之后):
find /the/folder -type f -exec sed -ibak 's/old/new/g' {} ';'
https://stackoverflow.com/questions/905144
复制相似问题