sed 是一个用来筛选与转换文本内容的工具。一般用来批量替换,删除某行文件

sed 命令详解

每个 sed 命令,基本可以由选项,匹配与对应的操作来完成

  1. # 打印文件第三行到第五行
  2. # -n: 选项,代表打印
  3. # 3-5: 匹配,代表第三行到第五行
  4. # p: 操作,代表打印
  5. $ sed -n '3,5p' file
  6. # 删除文件第二行
  7. # -i: 选项,代表直接替换文件
  8. # 2: 匹配,代表第二行
  9. # d: 操作,代表删除
  10. $ sed -i '2d' file

关键选项

  • -n: 打印匹配内容行
  • -i: 直接替换文本内容
  • -f: 指定 sed 脚本文件,包含一系列 sed 命令

    匹配

  • /reg/: 匹配正则

  • 3: 数字代表第几行
  • $: 最后一行
  • 1,3: 第一行到第三行
  • 1,+3: 第一行,并再往下打印三行 (打印第一行到第四行)
  • 1, /reg/ 第一行,并到匹配字符串行

    操作

  • a: append, 下一行插入内容

  • i: insert, 上一行插入内容
  • p: print,打印,通常用来打印文件某几行,通常与 -n 一起用
  • s: replace,替换,与 vim 一致

    sed examples

    查看手册

    1. $ man sed

    打印特定行

    p 指打印
    1. # 1p 指打印第一行
    2. $ ps -ef | sed -n 1p
    3. UID PID PPID C STIME TTY TIME CMD
    4. # 2,5p 指打印第2-5行
    5. $ ps -ef | sed -n 2,5p
    6. root 1 0 0 Sep29 ? 00:03:42 /usr/lib/systemd/systemd --system --deserialize 15
    7. root 2 0 0 Sep29 ? 00:00:00 [kthreadd]
    8. root 3 2 0 Sep29 ? 00:00:51 [ksoftirqd/0]
    9. root 5 2 0 Sep29 ? 00:00:00 [kworker/0:0H]

    打印最后一行

    $ 指最后一行

    注意需要使用单引号

  1. $ ps -ef | sed -n '$p'

删除特定行

d 指删除

  1. $ cat hello.txt
  2. hello, one
  3. hello, two
  4. hello, three
  5. # 删除第三行内容
  6. $ sed '3d' hello.txt
  7. hello, one
  8. hello, two

过滤字符串

grep 类似,不过 grep 可以高亮关键词

  1. $ ps -ef | sed -n /ssh/p
  2. root 1188 1 0 Sep29 ? 00:00:00 /usr/sbin/sshd -D
  3. root 9291 1188 0 20:00 ? 00:00:00 sshd: root@pts/0
  4. root 9687 1188 0 20:02 ? 00:00:00 sshd: root@pts/2
  5. root 11502 9689 0 20:08 pts/2 00:00:00 sed -n /ssh/p
  6. root 14766 1 0 Sep30 ? 00:00:00 ssh-agent -s
  7. $ ps -ef | grep ssh
  8. root 1188 1 0 Sep29 ? 00:00:00 /usr/sbin/sshd -D
  9. root 9291 1188 0 20:00 ? 00:00:00 sshd: root@pts/0
  10. root 9687 1188 0 20:02 ? 00:00:00 sshd: root@pts/2
  11. root 12200 9689 0 20:10 pts/2 00:00:00 grep --color=auto ssh
  12. root 14766 1 0 Sep30 ? 00:00:00 ssh-agent -s

删除匹配字符串的行

  1. $ cat hello.txt
  2. hello, one
  3. hello, two
  4. hello, three
  5. $ sed /one/d hello.txt
  6. hello, two
  7. hello, three

替换内容

s 代表替换,与 vim 类似

  1. $ echo hello | sed s/hello/world/
  2. world

添加内容

ai 代表在新一行添加内容,与 vim 类似

  1. # i 指定前一行
  2. # a 指定后一行
  3. # -e 指定脚本
  4. $ echo hello | sed -e '/hello/i hello insert' -e '/hello/a hello append'
  5. hello insert
  6. hello
  7. hello append

替换文件内容

  1. $ cat hello.txt
  2. hello, world
  3. hello, world
  4. hello, world
  5. # 把 hello 替换成 world
  6. $ sed -i s/hello/world/g hello.txt
  7. $ cat hello.txt
  8. world, world
  9. world, world
  10. world, world

注意事项

如果想在 mac 中使用 sed,请使用 gsed 替代,不然在正则或者某些格式上扩展不全。
使用 brew install gnu-sed 安装

  1. $ echo "hello" | sed "s/\bhello\b/world/g"
  2. hello
  3. $ brew install gnu-sed
  4. $ echo "hello" | gsed "s/\bhello\b/world/g"
  5. world