Linux基础-sed入门学习
# sed介绍
sed是一项Linux指令,功能同awk类似,差别在于,sed简单,对列处理的功能要差一些,awk的功能复杂,对列处理的功能比较强大。 sed全称 Stream Editor
# sed命令介绍
sed -e [option] 'command' file
# command 的格式构成
[addr]X[options]
一个命令由地址空间,命令字母,以及相应的命令选项(可选),比如命令:4,5p;q42;首先匹配地址空间4行与5行,然后执行打印命令p,命令p没有带可选参数,打印完成后执行 q 命令,
命令q带了可选项参数:42表明命令的退出 code 为:42;下面对此命令格式进行详细的介绍;
# [addr]
一个地址空间是后面跟的命令的执行匹配行的一个选择条件.后面的命令只对此地址空间匹配的行产生作用;如下命令:
sed '144s/hello/world/' input.txt > output.txt
Addresses determine on which line(s) the sed command will be executed. The following command replaces the word ‘hello’ with ‘world’ only on line 144:
如果没写地址空间选项,后面的命令将会在所有的行上进行操作,下面的命令将替换所有行中的单词:hello为world(注:只会替换一行中出现的第一个hello单词):
sed 's/hello/world/' input.txt > output.txt
除了使用行号,地址空间也可以包含一个正则表达式来匹配满足此表达式的行;下面的命令将会替换包含单词:apple的行的hello为world:
sed '/apple/s/hello/world/' input.txt > output.txt
一个地址范围通过两个地址指定,地址之间用,分隔;地址可以是数字,正则表达式,或者是两者的混合;下面的命令仅仅在4到17行,替换单词hello为world;
sed '4,17s/hello/world/' input.txt > output.txt
可以添加符号:!来取地址空间的补集:取反(在命令字母前面添加);下面的命令替换单词hello为world仅仅在那些不包含单词:apple的行中:
sed '/apple/!s/hello/world/' input.txt > output.txt
The following command replaces the word ‘hello’ with ‘world’ only in lines 1 to 3 and 18 till the last line of the input file (i.e. excluding lines 4 to 17):
sed '4,17!s/hello/world/' input.txt > output.txt