sed

sed : stream editor
注意: Mac使用的是BSD sed, linux上一般是GNU sed,命令使用方式有许多不同. Mac上使用最好安装一个gnu版本的.
sed, a stream editor
三十分钟学会SED
How to use GNU sed on Mac

1. sed : stream editor

命令格式 : sed [-hvn] [-e commands] [-f sedScript] [文本文件]

动作说明:

  • a : append
  • c : change, 取代n1~n2之间的行
  • d : delete
  • i : insert
  • p : print
  • s : substitute, 取代’s/str1/str2/‘
  • n : 处理完成后不打印到stdout

以下操作以/etc/profile文件为示例

2. 新增: sed a

在某一行后面新增一行

1
2
3
4
5
6
7
8
#在第二行后面插入新的一行
$ sed '2a\Insert a new line after row 2!' file

#在最后一行后面插入新的一行
$ sed '$a\最后一行后面插入一行' file

#在每一行后面插入新的一行
$ sed '1,$a\每一行后面都插入新的一行' file


3. 删除: sed d

1
2
3
4
5
6
7
8
9
10
#删除第一行第二行第三行
$ sed -e '1d' -e '2d' -e '3d' profile
$ sed -e '1d\n2d\n3d' profile
# sed -e '1,3d' profile

#删除所有空白行
$ sed '/^$/d' profile

#删除所有包含PATH的行
$ sed '/PATH/d' profile

构建一个命令文件来执行command.txt

1
2
3
4
$ echo -e '1d\n2d\n3d' > command.txt #使用-e是为了行末尾不能有\n(trailing newline),否则sed执行会有问题

#使用sed执行删除操作
$ sed -f command.txt profile


4. 打印: sed p

1
2
3
4
5
6
7
8
#每一行打印两次
$ sed -e '' -e 'p' profile

#只打印第三行
$ sed -n '3p' profile

#第三行打印2次,其他的打印一次
$ sed -e '3p' profile

$代表文件最后一行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#只打印最后一行
$ sed -n '$p' profile

#打印第10行到最后一行
$ sed -n '10,$p' profile

#每行打印两次
$ sed '10,$p' profile

#打印包含字符串PATH的行
$ sed -n '/PATH/p' profile

#nl : line number filtering
nl profile | sed '/PATH/p'

#打印不包含字符串PATH的行
$ sed -n '/PATH/!p' profile


5. 替换: sed s

  • 将每行第一个PATH替换为path
    1
    $ sed 's/PATH/path/' profile
  • 将每行所有的PATH替换为path
    1
    2
    #global substitute
    $ sed '/s/PATH/path/g' profile