首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >sed初学者:更改文件夹中的所有事件

sed初学者:更改文件夹中的所有事件
EN

Stack Overflow用户
提问于 2009-05-25 10:42:58
回答 8查看 103.1K关注 0票数 116

我需要对文件夹(及其子文件夹)中的所有文件执行正则表达式查找和替换。要做到这一点,linux shell命令是什么?

例如,我想对所有文件运行此命令,并用新的替换文本覆盖旧文件。

sed 's/old text/new text/g' 
EN

回答 8

Stack Overflow用户

发布于 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选项。

票数 66
EN

Stack Overflow用户

发布于 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读取文件之前将其截断。

票数 8
EN

Stack Overflow用户

发布于 2009-05-25 02:50:58

我可以建议(在备份您的文件之后):

find /the/folder -type f -exec sed -ibak 's/old/new/g' {} ';'
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/905144

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档