Leif160519的blog
foo用字符串bar替换,然后将该文件内容输出到标准输出sed -e 's/foo/bar/' myfile
g 使得 sed对文件中所有符合的字符串都被替换sed -e 's/foo/bar/g' myfile
i使得 sed修改文件sed -i 's/foo/bar/g' myfile
m 开头的文件sed -i 's/foo/bar/g' ./m*
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 替换文件中的字符串