Leif160519的blog Leif160519的blog

——————

目录
sed 替换文件中的字符串
/    

sed 替换文件中的字符串

1.将 myfile 文件中每行第一次出现的foo用字符串bar替换,然后将该文件内容输出到标准输出

sed -e 's/foo/bar/' myfile

2.g 使得 sed对文件中所有符合的字符串都被替换

sed -e 's/foo/bar/g' myfile

3.选项 i使得 sed修改文件

sed -i 's/foo/bar/g' myfile

4.批量操作当前目录下以 m 开头的文件

sed -i 's/foo/bar/g' ./m*

5.``括起来的grep命令,表示将grep命令的的结果作为操作文件

sed -i 's/foo/bar/g' `grep foo -rl --include="m*" ./`

grep 命令中,选项r表示查找所有子目录,l表示仅列出符合条件的文件名,用来传给sed命令做操作,--include="m*" 表示仅查找 m开头的文件

操作示例:

sed -i '' 's/<img src=\"http:\/\/website\.cn\/f\/30/<img src=\"30/g' ./*.htm
错误:
command a expects \ followed by text

选项i的用途是直接在文件中进行替换。为防止误操作带来灾难性的后果,sed在替换前可以自动对文件进行备份,前提是需要提供一个后缀名。mac osx下是强制要求备份的,centos下是可选的

sed -i '.bak' 's/foo/bar/g' ./m*

如果不需要备份文件,使用空字符串来取消备份,mac osx下可以使用如下命令完成替换操作:

sed -i '' 's/foo/bar/g' ./m*
sed: RE error: illegal byte sequence’

可设置环境变量解决

export LC_COLLATE='C'
export LC_CTYPE='C'

“The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.” – Tom Cargill

标  题sed 替换文件中的字符串
作  者Leif160519
出  处https://github.icu/articles/2019/09/06/1567761635359.html
关于博主:坐标南京,运维工程师,如有问题探讨可以直接下方留言。
声援博主:如果您觉得文章对您有帮助,可以评论、订阅、收藏。您的鼓励是博主的最大动力!