shell 玩转sed,你不知道的用法

sed 是 stream editor(流编辑器)的缩写

操作 作用
p 打印文本行(print)
n 取消默认输出
d 删除(delete)
s 字符串替换(substitude)
a 追加新的文本(append)

示例文件

1
2
3
4
5
6
7
# cat example.conf
username=this username_2=this
password=that

url=this

path=this

1.替换

sed 命令会将 s 之后的字符视为命令分隔符,这允许我们更改默认的分隔符,如:
sed 's:this:new:g' example.conf
sed 's|this|new|g' example.conf
如果作为分隔符的字符出现在模式中,必须使用 \对其进行转义

sed 's/this/new/' example.conf 替换 每行首次 匹配的内容

ouput:

1
2
3
4
5
6
username=new  username_2=this
password=that

url=new

path=new

sed 's/this/new/g' example.conf g标记可以使sed执行全局替换

sed 's/this/new/2g' example.conf #g可以使sed替换第N次出现的匹配

将1-4行的url换成address, s代表替换
sed '1,4s/url/address/g' example.conf

2.删除

sed '2,4d' example.conf 删除第2到4行

sed -e '/url/d' example.conf 删除含”url”的行,输出到终端,实际没有替换文件

sed '/appleapple/d;$d' example.conf 删除包含appleapple的行和最后一行($)

移除空行
sed '/^$/d' file 空行可以用 ^$ 进行匹配,最后的 /d 告诉sed不执行替换操作,而是直接删除匹配到的空行

检查替换内容
sed -n 's/mysql_host_key/mysql_host_key_new/g'p test-application.yml

-n停止修改后的文本的输出。然后使用p打印修改后的行

macOS 不一样的 sed

报错如下

1
2
sed -i 's/mysql_host_key/mysql_host_key_new/g'  test-application.yml
sed: 1: "test-application.yml": undefined label 'est-application.yml'

原因: The sed command is a bit different in Mac OS X, the ‘-i’ option required a parameter to tell what extension to add for the backup file.

解决办法:
sed -i '.bak' 's/mysql_host_key/mysql_host_key_new/g' test-application.yml

参见 https://mkyong.com/mac/sed-command-hits-undefined-label-error-on-mac-os-x/


✍TIP

  1. 首先使用不带 -i选项的sed命令,查看结果是否符合预期;再加入 -i选项将更改写入文件。

  2. sed -i.bak 's/abc/def' file 这时的sed不仅替换文件内容,还会创建一个名为file.bak的文件,其中包含着原始文件内容的副本;如果对一个文件多次执行,则xx.bak文件只会是上一个文件的副本

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2019-2024 John Doe
  • Visitors: | Views:

请我喝杯咖啡吧~