sed选项详解(options)
几天时间把 sed and awk 101hacks 的sed部分看完了,觉得功能甚是强大,在这里记录下sed的一些参数说明
sed [options] {sed-commands} {input-file}
主要Options 有:n , i , c, f, e, l, h, V
详解:
-n: 不输出原文件,只输出命令执行后的结果(The sed option -n suppresses the default printing that happens as part of the standard sed flow. )
sed -n 'p' /etc/passwd
你也可以使用 --quiet, or –-silent 来代替 -n. 他们提供相同的功能。
-i: 修改后文件替换原文件( Sed option -i typically uses a temporary file to create the changes and renames it to the original input-file when the operation is completed. )
sed -i 's/John/Johnny/' employee.txt
该参数会把变更写入到原文件(employee.txt)
等同于:
sed 's/John/Johnny/' employee.txt > new-employee.txt
mv new-employee.txt employee.txt
为安全起见,一般使用:
sed -ibak 's/John/Johnny/' employee.txt
代替。该命令会在修改前生成一个备份文件(文件名为原名末尾追加bak),-ibak等同于--in-place=bak,--in-place=bak 更灵活,可以变更追加的表示符(bak)
-c: 保持文件归属不变
由于-i 命令是重新生成了文件并把新文件重命名为原文件,这会导致文件的ownership 改变,-c 命令的存在就是为了防止这个发生的。所以这个命令需要和-i 一同使用。
sed -ibak -c 's/John/Johnny/' employee.txt
-f: 使用命令文件
sed -n -f test-script.sed /etc/passwd
sed -n --file=test-script.sed /etc/passwd
命令写到test-script.sed文件中,直接调用sed -f filename 就ok
也可以把#!/bin/sed -f 添加到sed命令文件首行,直接调
./test-script.sed /etc/passwd
就可以执行
-e: 执行一个sed命令
sed -n -e '/root/ p' /etc/passwd sed -n --expression '/root/ p' /etc/passwd
sed -n -e '/^101/p' -n -e '/Manag/p' employee.txt
多个-e之间是或者的关系,满足条件的都会输出
-l:指定行长度
sed -n -l 20 'l' employee.txt sed -n --line-length=20 employee.txt
超过设定的长度后换行,必须和'l'命令一块使用
-h或--help:显示帮助;
-V或--version:显示版本信息。
发现错误或不足指出烦请指出,谢谢,欢迎转载,请注明出处Jaxlinda。