程序员利器

SED 命令笔记一命令参数

2020-02-23  本文已影响0人  jimson_ma

Sed 是一个流式编辑器(流编辑器),与其他编辑器不同的是他可以在输入流(文件或者输入管道)中对文件进行处理或者转换(增删改查)。

基本使用方法: sed SCRIPT INPUTFILE
以文本替换为例(也是最常见的用法): Script 以s开头表示文本替换:

echo 'hello world' >  input.txt
cat input.txt #hello world
sed 's/hello/word/' input.txt > output.txt
cat output.txt.  #world world

如果不指定input 文件则会从stdin 中获取内容, 下面三个命令的结果是相同的:

sed 's/hello/world/' input.txt > output.txt
sed 's/hello/world/' < input.txt > output.txt
cat input.txt | sed 's/hello/world/' > output.txt 
echo 'hello world' | sed 's/hello/world/' > output.txt 

常见参数:

-i : in-place模式,表示编辑文件而不是将其打印出来。 此命令在mac 和linux 有点不同,具体参见man sed

# for linux
sed -i 's/hello/world/' input.txt
cat input.txt #world world

#for mac os
sed -i '.bak' 's/hello/world/' input.txt
cat input.txt #world world
cat input.txt.bak #hello world

-e: 指定命令的SCRIPT内容。可以使用多次指定多个SCRIPT. 其实在SCRIPT中使用;也可以组合多个命令。 下面命令的结果是相同的。

echo -e 'hello world' | sed -e 's/hello/A/' -e 's/world/B/'  # A B
echo -e 'hello world' | sed 's/hello/A/' | sed 's/world/B/'  # A B
echo -e 'hello world' | sed 's/hello/A/;s/world/B/'  # A B

验证下命令是顺序执行的, 修改命令如下:

echo -e 'hello world' | sed -e 's/hello/A/' -e 's/A/B/'  # B world
echo -e 'hello world' | sed 's/hello/A/' | sed 's/A/B/'  # B world
echo -e 'hello world' | sed 's/hello/A/;s/A/B/'  # B world

-n:阻止命令输出到stdout

 echo -e 'hello world' | sed 's/hello/A/' # A world
 echo -e 'hello world' | sed -n 's/hello/A/' # ~~ nothing

-f:以文件的形式指定SCRIPT

echo 's/hello/world/' > script
echo -e 'hello world' | sed -f script # A world

指定多个目标文件

echo 'ahello' > output.txt
sed -e 's/hello/world/' input.txt output.txt
#world world
#aworld
上一篇 下一篇

猜你喜欢

热点阅读