sed基本用法

sed可以替换给定文本中的字符串,通过正则表达式来实现。

例如   

sed 's/pattern/replace_string/' file

1、后缀/g意味着sed会替换每一处匹配。但是有时候并不需要替换前N处。有一个选项可以忽略前N处匹配,并从N+1处开始匹配。

echo this thisthisthis | sed 's/this/THIS/2g'
thisTHISTHISTHIS

2、移除空白行

sed '/^$/d' file

3、已匹配字符串标记&

echo this is an example | sed 's/\w+/[&]/g'
[this] [is] [an] [example]

正则表达式\w\+匹配每一个单词,然后用[&]替换。&对应于之前所匹配的单词。

4、子串匹配标记\1

echo this is digit 7 in a number | sed 's/digit \([0-9]\)/\1/'
this is 7 in a number

对于匹配到的第一个子串,其对应的标记是\1,匹配到的第二个子串是\2,往后依次类推。

echo seven EIGHT | sed 's/\([a-z]\+\) \([A-Z]\+\)/\2 \1/'
EIGHT seven

5、组合多个表达式

sed 'expression' | sed 'expression' 等价于 $ sed 'expression' ; 'expression'

6、引用

text=hello
echo hello world | sed "s/$text/HELLO/"
HELLO world

以后遇到什么更好的表达式再更新。

原文地址:https://www.cnblogs.com/dgy5554/p/3973426.html