一、简介
sed命令可依照脚本的指令来处理、编辑文本文件,可以对文本文件进行增、删、改、查等操作,支持按行、按字段、按正则匹配文本内容,灵活方便,特别适合于大文件的编辑,同时在脚本中运用。
二、选项
选项 | 参数说明 |
---|---|
-e | 多重sed指令进行编辑,注意顺序会影响结果 |
-f | 指定sed命令执行后保存的文件名 |
-n | 取消默认输出,只打印处理过的行 |
-i | 直接修改要处理的文件,默认为预览 |
三、文本编辑
编辑指令 | 功能详解 |
---|---|
a:追加 | 向匹配的行执行追加操作 |
d:删除 | 将匹配的行进行删除 |
c:修改 | 更改匹配行的内容 |
s:替换 | 将匹配的内容进行替换 |
i:插入 | 在匹配行前插入内容 |
p:打印 | 打印匹配的内容,一般加入-n参数 |
四、具体实例
4.1 追加
在匹配行后增加一行:
sed -i '2atest' test.txt
4.2 删除
将匹配的内容行进行删除:
sed -i '/test/d' test.txt
删除指定的行:
sed -i '3d' test.txt
删除多行:
sed -i '1,10d' test.txt
删除最后一行:
sed -i '$d' test.txt
删除第一行:
sed -i '^d' test.txt
删除1~2行其他行:
sed -i '1,2!d' test.txt
删除空行:
sed -i '/^$/d' test.txt
可以删除内容为多个空格/tab组成的行。
sed -i /^[[:space:]]*$/d test.txt
删除从匹配到123的行到最后一行:
sed '/123/,$d ' test.txt
删除不匹配123或abc的行:
sed '/123\|abc/!d' test.txt
4.3 替换
替换文本内容(注意该替换只替换每一行第一个匹配到的内容):
sed -i 's/hello/world/' test.txt
替换指定行文本内容:
sed -i '3s/hello/world/' test.txt //将第三行中hello替换成world
替换全文所有匹配的内容:
sed -i 's/hello/world/g' test.txt
将test.txt中文件每一行的hello替换成world并写到test2.txt文件中:
sed -n 's/hello/world/gpw test2.txt' test.txt
将匹配的内容加上一个括号:
sed -i 's/^ [0-9]/(&)/' test.txt (&表示匹配的内容也可以用\1代替)
在每一行末尾追加world内容:
sed -i 's/$/&'world'/' test.txt
4.4 打印
打印匹配到的内容的行:
sed -n '/hello/p' test.txt
打印第一行到匹配到hello的行:
sed -n '1,/hello/p' test.txt
打印匹配到内容的行号和内容:
sed -n '/hello/{=;p}' test.txt
只打印匹配到内容的行号:
sed -n '/hello/=' test.txt
4.5 从文件中读内容
将一个test1文件内容插入test2文件中到匹配到hello的行后面:
sed '/hello/r test1.txt' test2.txt
向文件中写入内容:
将test1文件中匹配到hello或者world的行的内容写入到test2文件中:
sed '/hello\|world/w test2.txt' test1.txt
4.6 sed带变量执行
方式1: 使用单引号,变量处使用单引号+双引号把变量包括起来
sed -n '/'"${a}"'/=' defconfig
方式2: 使用双引号,变量直接引用即可
sed -n "/${a}/=" defconfig
4.7 多行合并成一行
cat old_file.txt | tr '\n' ' ' >new_file.txt