sed编辑器(二)
更改行:工作方式与插入命令相同。
(1)sed ' 3c\ > This is a test. '#更改第三行中的文本。 (2)sed '/number 3/c\ > This is a changed line of text.' fiel #寻址匹配文本模式 (3)sed '2,3c\ >This is a new line of text. ' file #在更改命令中,可以使用地址范围,但使用单一文本行替换范围行。
变换命令:
[address]y/inchars/outchars/
变换命令(y)是唯一对单个字符进行操作的sed编辑器命令。变换命令将inchars和outchars的值进行一对一映射。将inchars中的第一个字符转换为outchars中的第一个字符。将inchars中的第二个字符转换为outchars中的第二个字符。这样的映射一直持续到完成指定的字符长度。如果inchars和outchars的长度不同,sed编辑器将生成错误消息。变换命令是全局命令,自动对文本发现的任意字符进行转换。$cat data This is line number 1 This is line number 2 This is line number 3 This is line number 4 This is line number 5 This is line number 6 This is line number 7 This is line number 8 This is line number 9 This is line number 10 This is line number 11 This is line number 12 This is line number 1 again This is yet another line This is the last line in the file $sed 'y/123/opq/' data This is line number o This is line number p This is line number q This is line number 4 This is line number 5 This is line number 6 This is line number 7 This is line number 8 This is line number 9 This is line number o0 This is line number oo This is line number op This is line number o again This is yet another line This is the last line in the file
打印命令:
打印文本行的p命令(打印数据流中部分行,改变某行之前查看该行。)
$sed -n '/3/{ > p > s/line/test/p > ' data This is line number 3 This is test number 3 #先搜索包含数字3的行,然后执行两个命令。首先,脚本使用p命令打印该行的原始版本,然后使用s命令替换文本,并使用p标记打印最终得到的文本。输出显示了原来的行文本和新的行文本。
打印行号的=命令
$ sed -n '/number 4/{ > = > p } ' data 4 This is line number 4.
- 列出行的l命令:允许打印数据流中的文本和不可打印的ASCII字符。
写文件w命令:
[address]w filename
filename可以指定为相对或绝对路径,但在任意一种情况下,运行sed编辑器的用户必须对该文件有写权限。$ sed '1,2w test' data This is line nuumber 1. This is line number 2. This is line number 3. This is line number 4. $ cat test This is line number 1. This is line number 2.
从文件读取数据r命令:
[address]r filename
filename参数可以为包含数据的文件指定相对或绝对路径。对于读命令,不能时欧诺个地址范围。只能指定点哪一的行号或文本模式地址。sed编辑器在该地址后插入文件中的文本。读命令的一个很好的用途是和删除命令一起使用,用另一个文件中的数据替代一个文件中的占位符。$cat data This is an added line. This is the second added line. $sed '3r data' data This is line number1 This is line number2 This is an addes line. This is the second added line.