0525 linux sed 文本处理 反选 倒序 分组处理 jump bug

0525 linux sed 文本处理 反选 倒序 分组处理 jump bug

1. sed如何反选打印行

$ cat data2.txt
This is the header line.
This is the first data line.
This is the second data line.
This is the last line.

$ sed -n ‘/header/!p’ data2.txt
This is the first data line.
This is the second data line.
This is the last line.

在p前面加个感叹号

2.sed如何反选最后一行,就是除了最后一行,其他都选上。

背景:sed的N命令,多行处理命令,是无法处理最后一行的,因为最后一行的下一行它读不到了,所以就放弃处理了。

这个是没有读到最后一行的情况,可以看到最后一行的目标文本并没有被替换。
$ sed 'N;
> s/System\nAdministrator/Desktop\nUser/
> s/System Administrator/Desktop User/
> ’ data4.txt
On Tuesday, the Linux Desktop
User’s group meeting will be held.
All System Administrators should attend.

这个是反选了除了最后一行的所有行: $!N
$表示最后一行,!表示反选,N表示把当前行和下一行当作一行处理。
$ sed '$!N;
> s/System\nAdministrator/Desktop\nUser/
> s/System Administrator/Desktop User/
> ’ data4.txt
On Tuesday, the Linux Desktop
User’s group meeting will be held.
All Desktop Users should attend.

3.linux如何倒行序输出文本

cat text 正序输出,大家都知道
tac text 倒序输出,刚好和cat相反,非常好记

4.sed如何分组匹配处理字符串 branch lable

原文本
$ cat data2.txt
This is the header line.
This is the first data line.
This is the second data line.
This is the last line.

普通的区间处理,2,3b 就是跳过第二行和第三行
$ sed ‘{2,3b ; s/This is/Is this/ ; s/line./test?/}’ data2.txt
Is this the header test?
This is the first data line.
This is the second data line.
Is this the last test?

先定义跳过的区间与标签,然后第一条处理命令会跳过它来执行,然后用区间标签 :jump 来指定区间来执行区间命令。
$ sed ‘{/first/b jump1 ; s/This is the/No jump on/
> :jump1
> s/This is the/Jump here on/}’ data2.txt
No jump on header line
Jump here on first data line
No jump on second data line
No jump on last line


如果把区间标签的定义放在最后面,那么处理命令就会循环执行,直到匹配不到为止。因为 /,/b start 这个匹配命令应该是会跳回第一行。第一个替换命令应该是被省略了。

多行形式(打出一个引号后再在控制台按回车它会换行而不是执行命令。
$ echo “This, is, a, test, to, remove, commas.” | sed -n ‘{
> :start
> s/,//1p
> /,/b start
> }’

单行形式
echo “This, is, a, test, to, remove, commas.” | sed -n ‘{:start s/,//1p; /,/b start}’

This is, a, test, to, remove, commas.
This is a, test, to, remove, commas.
This is a test, to, remove, commas.
This is a test to, remove, commas.
This is a test to remove, commas.
This is a test to remove commas.

5.疑似sed jump bug 为什么sed分组不起作用了

$ cat 0525test
This is the last line.
This is the second data line.
This is the first data line.
This is the header line.

$ sed ‘{/first/b jump1 ; s/This is the first/No jump on/ ; :jump1 ; s/This is the/Jump here on/}’ 0525test
Jump here on last line.
Jump here on second data line.
Jump here on first data line.
Jump here on header line.

为什么只有一行匹配到了,但是全部行都被替换了?有first的跳过了, 不会被第一个替换命令处理到。但其他行没有first怎么会被第二个替换命令处理到呢?难道这是sed的bug?第一个替换命令的匹配字符中不能有跳过标记的字符。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值