linux 命令 — sed

sed

stream editor,流编辑器

查找替换

sed 's/pattern/replace_string/' file
替换每一行第一次出现的pattern,将替换后的文本输出到stdout,'/'是定界符,可以使用任意的定界符,如果在pattern或者replace_stirng中出现定界符的话,使用''进行转义

sed 's/http:///https://' url.txt
把每一行第一次出现的http替换为https

sed 's/pattern/replace_string/g' file
替换所有的pattern,将替换后的文本输出到stdout,g表示替换每一行中的出现的所有pattern

sed 's/pattern/replace_string/2g' file
替换第三次开始出现的的pattern,将替换后的文本输出到stdout,ng表示替换每一行中从第(n+1)次出现的pattern

sed -n 's/pattern/str/g'
输出所有替换后的行

cat file | sed -n '/pattern/p'
输出搜索到的行,-n表示只输出匹配到的行(默认输出所有行)

sed -i 's/pattern/str/g' file
直接将替换后的内容写入到源文件中

sed -e 's/pattern1l/str1/g' -e 's/pattern2/str2/g' file
进行多处编辑

移除空白行

sed '/^$/d'
^$: 匹配空白行
d: 删除匹配到的行

已匹配字符串标记&

echo this is an example | sed 's/w+/[&]/g'
输出:[this] [is] [an] [example]
w: 正则表达式元字符,表示匹配单个单词(数字、字母,下划线)
+: 正则表达式,匹配一次或者多次,"+"对"+" 进行转义
&: 表示前面pattern匹配到的字符串

echo BIG small | sed 's/([A-Z]+) ([a-z]+)/2 1/'
输出:small BIG
1: 表示pattern中第一个 (pattern) 匹配到的子串,2表示第二个,以此类推

组合多个表达式

sed 'exp1' | sed 'exp2'
等价于
sed 'exp1'; 'exp2'
等价于
sed 'exp1 exp2'
等价于
sed -e exp1 -e exp2

双引号,引用

sed一般使用单引号包围表达式,如果要使用shell变量,则使用双引号,因为在shell中shell不会对单引号内的内容进行解析,对双引号中的部分符号会进行解析,比如"$"
test=hello; echo hello WORLD | sed "s/$test/HELLO/"
输出:HELLO WORLD

模式空间

pattern space: 模式空间,处理文件一行的临时缓冲区,处理完一行之后把模式空间的内容打印到stdout,然后自动会清空缓存
hold space: 保持空间,不糊自动清空的缓冲区,使用gGhHd等命令操作

d: 删除pattern space的内容,开始下一个循环
h、H: 复制/追加pattern space到hold space
g、G: 复制/追加hold space 到pattern space
x: 交换pattern space 和 hold space`的内容

$ cat num.txt
one
two
three

$ sed '1!G;h;$!d' num.txt
three
two
one

对每一行执行命令 '1!G;h;$!d'
第一行:
1!G: 不执行G,
h: 复制pattern space内容——one到hold space
$!d: 删除pattern space

执行完之后:
pattern space: 空
hold space:
one

第二行:
1!G: 追加hold space 内容到pattern space
h: 复制pattern space内容到hold space
$!d: 删除pattern space

执行完之后:
pattern space: 空
hold space:
two
one

第三行:
1!G: 追加hold space到pattern space
h: 复制pattern space到hold space
$!d: 不删除pattern space

执行完之后:
pattern space:
three
two
one
hold space:
three
two
one

转换大小写

这个功能是gnu sed的extension
L: 转换replacement为小写,直到遇到E、U
l: 转换下一个char为小写
U: 转换replacement为大写,直到遇到L、E
u: 转换下一个char为大写
E: 转换大小写的终止符,终止以L、U开始的转换

echo 'a-b-' | sed 's/(b?)-/xu1/g'
输出:axxB

echo 'a-b-' | sed 's/(b?)-/u1x/g'
输出:aXBx

s命令的一般形式
s/regex/replacement/flag
可用的flag
g: 将替换应用到所有地方,而不是搜索到的第一个地方
number: 替换第number个地方
i、I: 不区分大小写

原文地址:https://www.cnblogs.com/sunshine-2015/p/7148211.html