sed 流编辑脚本
语法: sed [OPTION]... {script-only-if-no-other-script} [input-file]...
通常调用sed的格式:
sed SCRIPT INPUTFILE...
如果指定了标准输入文件,格式大概是这样子:
sed ’s/hello/world/’ input.txt > output.txt
sed ’s/hello/world/’ < input.txt > output.txt
如果没有指定标准输入文件,将会从标准输入中接收文件,大概是这样子:
cat input.txt | sed ’s/hello/world/’ - > output.txt
sed写出的内容到标准输出,使用-i选项可以修改输入的文件内容去替代标准输出:
sed -i ’s/hello/world/’ file.txt
使用-n可以抑制输出,然后配合p命令,可以输出指定的行数:
sed -n ’45p’ file.txt
sed会将多个输入文件,视为一个长文件,例如下面这样会打印one.txt的第一行和three.txt的最后一行:
sed -n ’1p ; $p’ one.txt two.txt three.txt
如果没有-e或-f选项。sed会使用第一个不是选项的参数作为脚本,后面跟的非选项参数作为输入文件。如果-e或-f选项指定了脚本,那所有的非选项参数将会作为输出文件。
下面的示例是等效的:
sed ’s/hello/world/’ input.txt > output.txt
重要的命令行选项:
sed脚本语法:
[addr]X[options]
X是sed单个字符命令,[addr] 是行地址,如果指定了[addr],则X只会作用于匹配的行,[addr] 可以是一个行数字,或一个正则的表达式,或行的范围,附加[options] 选项用于某些sed命令。
比如:sed ’30,35d’ input.txt > output.txt
删除30至50行的数据
示例:
sed ’/^foo/q42’ input.txt > output.txt
/^foo/是一个正则表达式,假如匹配到值,退出状态码42;假如没有匹配到值(且没有发生错误)退出状态码0.
下面所有的命令都是等效的。
sed ’/^foo/d ; s/hello/world/’ input.txt > output.txt
sed -e ’/^foo/d’ -e ’s/hello/world/’ input.txt > output.txt
echo ’/^foo/d’ > script.sed
echo ’s/hello/world/’ >> script.sed
sed -f script.sed input.txt > output.txt
echo ’s/hello/world/’ > script2.sed
sed -e ’/^foo/d’ -f script2.sed input.txt > output.txt
sed命令:
{ cmd ; cmd ... } 几个命令组
sed命令中最重要的一个命令s.
在任何给定的s命令中,/字符可以统一替换为任何其他单个字符。只有在/字符前面加上\字符时,才能在regexp或替换中出现/字符(或替代它的任何其他字符)。
反斜杠转以后的字母,具有特殊的含义:
\L \l \U \u \E |
Turn the replacement to lowercase until a \U or \E is found, Turn the next character to lowercase, Turn the replacement to uppercase until a \L or \E is found, Turn the next character to uppercase, Stop case conversion started by \L or \U. |
后面的flag,可以有下面这些值(不全,重要的记录):
g:将替换应用于regexp的所有匹配项,而不仅仅是frst。
e:This command allows one to pipe input from a shell command into pattern space. If a substitution was made, the command that is found in pattern space is executed and pattern space is replaced with its output. A trailing newline is suppressed; results are undefned if the command to be executed contains a nul character. This is a GNU sed extension.
原文:https://www.cnblogs.com/wonchaofan/p/13527138.html