sed:s命令

来源:互联网 发布:淘宝天猫店要多少钱 编辑:程序博客网 时间:2024/05/16 07:19

shell脚本最常见的一个用途就是处理文本文件。

检查日志文件、读取配置文件、处理数据元素,shell脚本可以帮助我们将文本文件中各种数据的日常处理任务自动化。


sed (常见的命令行编辑器之一)

stream editor流编辑器 (vim 交互式文本编辑器)

编辑器命令

s命令:斜线/隔出两个字符串,用第二个替换第一个(每行默认只替换第一处)

echo "This is a test" | sed 's/test/big test/'

This is a big test

-e可以执行多个命令:

vim data1.txt

The quick green fox jumps over the lazy cat.

sed -e 's/brown/green/;s/dog/cat/;' data1.txt

The quick green fox jumps over the lazy cat.


-f执行文件

vim script1.sed

s/brown/green/
s/fox/elephant/
s/dog/cat/

sed -f script1.sed data1.txt


4种替换标记

数字:表面替换第几处内容

sed 's/test/trial/2' data4.txt

g:替换全部内容

p:打印原先行(-n 禁止sed编辑器输出,配合p使用只输出被修改的行)

sed -n 's/test/trial/p' data5.txt

w file:将替换结果写入文件file

sed 's/test/trial/w test.txt' data4.txt

cat test.txt


特殊字符串替换:\转义符

    !字符串分隔符


替换特定行:行寻址

sed '2s/dog/cat/' data1.txt

The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy cat.
The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.

sed '2,$s/dog/cat/' data1.txt




(本文为《LINUX命令行与shell脚本编程大全》学习笔记,不作商用)

原创粉丝点击