sed(stream editor)是一种流编辑器,它是文本处理中非常中的工具,能够完美的配合正则表达式使用,功能不同凡响。
处理时,把当前处理的行存储在临时缓冲区中,称为“模式空间”(pattern space),接着用sed命令处理缓冲区中的内容,处理完成后,把缓冲区的内容送往屏幕。接着处理下一行,这样不断重复,直到文件末尾。文件内容并没有改变,除非你使用重定向存储输出。Sed主要用来自动编辑一个或多个文件;简化对文件的反复操作;编写转换程序等。
sed -i 's/regexp/replacement/g' FileName # The -i option, introduced in GNU sed, allows in-place editing of files (actually, a temporary output file is created in the background, and then the original file is replaced by the temporary file). # The s stands for substitute, while the g stands for global, which means that all matching occurrences in the line would be replaced.
1、简单字符串替换
[root@localhost ~]# echo I Love USA | sed 's/USA/China/g' I Love China # 将字符串中的“USA”替换成“China”
2、正则表达式替换
[root@localhost ~]# echo II67676JJ | sed 's/[0-9]/*/g' II*****JJ # 将字符串中的数字替换成“*”
3、批量替换文件内容
[root@localhost ~]# sed -i 's/regexp/replacement/g' FileName # 替换单个文件 [root@localhost ~]# sed -i 's/regexp/replacement/g' `ls` # 替换当前目录下的所有文件 [root@localhost ~]# sed -i 's/regexp/replacement/g' `grep regexp -rl path` # 批量替换多个文件
注意:安全第一。替换前请备份好文件以免造成不必要的损失,切记,切记,切记!