sed常见格式:
sed -option 'command/pattern1/pattern2/pattern flag' 1.txt
-option包括:
-n: noprint。常与pattern flag: p合用
-e: 执行多个sed命令
-f: 调用文件中的sed脚本
-i: 编辑文件。例子:
[oracle@odilab ~]$ cat 1.txt
a
b
c
d
e
f
[oracle@odilab ~]$ echo "," >> 1.txt
[oracle@odilab ~]$ sed -i 's/,//' 1.txt
[oracle@odilab ~]$ cat 1.txt
a
b
c
d
e
f
command:
s: 替换
d: 删除
a: 追加 append
n: next
pattern flag:
g: global
p: print
i: ignore case
w file: write to file,将会覆盖原有内容。请看例子。
[oracle@odilab ~]$ sed -n '/a/w 2.txt' 1.txt
[oracle@odilab ~]$ cat 2.txt
a
a
将最后一行写入2.txt文件
[oracle@odilab ~]$ sed -n '$w 2.txt' 1.txt
[oracle@odilab ~]$ cat 2.txt
a
与-e搭配,将不同内容写入2.txt. 这个方法不是最优的,仅仅为了说明命令用法。
[oracle@odilab ~]$ sed -n -e '/a/w 2.txt' -e '/b/w 2.txt' 1.txt
[oracle@odilab ~]$ cat 2.txt
a
b
a
--Removing the last comma from each line.
sed 's/,$//g' xxx.file
--执行文件中的sed命令
sed -f <file> < <input.txt>
--打印指定行 /p参数
sed默认情况下打印整个文件,-n将只打印匹配行。
[oracle@odilab ~]$ cat 1.txt
a
b
aa
[oracle@odilab ~]$ sed '1p' 1.txt
a
a
b
aa
[oracle@odilab ~]$ sed -n '1p' 1.txt
a
[oracle@odilab ~]$ sed -n '1,2p' 1.txt
1318932 ./4.txt
1270876 ./data/IA_Adjustments.dat.good
-n = noprint
-n , p 组合相当于grep命令
这里'1,2p' 表示打印第1到第2行
--删除匹配的行
--打印行号 =参数
该功能用grep实现更简单:
--删除匹配的行
[oracle@odilab ~]$ sed '/a/d' 1.txt
b
注:文件并没有被删除,只是在屏幕上显示而已。
[oracle@odilab ~]$ sed '/a/d' 1.txt > 2.txt
[oracle@odilab ~]$ cat 2.txt
b
这时,结果被写入另一个文件。
--打印行号 =参数
[oracle@odilab ~]$ cat 1.txt
a
b
c
d
e
f
a
[oracle@odilab ~]$ sed -n '/a/{=;p}' 1.txt |sed '{N;s/\n/ /}'
1 a
7 a
= 打印的行号和文件内容不在同一行。需要N参数将下一行读入,然后将换行符替换为空格。
该功能用grep实现更简单:
[oracle@odilab ~]$ grep -n "a" 1.txt
1:a
7:a