gpt4 book ai didi

linux - sed 命令的排序因未知原因而中断

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:49:51 24 4
gpt4 key购买 nike

输入

文件.txt

Start
1
2
3
4
Start
5
6
7
8

问题

我正在研究 sed 以找出从 Start 之间获取数据的不同方法。

我制作的一个脚本是

sed ':2;h;$!N;$b1;/\n.*Start[^\n]*$/{:1;$!x;/5/p;x;s/.*\n//};$!b2;d'

脚本解释

:2 #A label for the break point

;h #Hold all the lines currently in the pattern buffer, i use this before getting the next line so that it doesn't have the next start.

;$!N # Gets the next line for every line except the last

;$b1 # Breaks to label 1 on the last line. This is to bypass having to see start to enter the block


;/\n.*Start[^\n]*$/ # If start is on the last line of pattern buffer then execute the next block

{ #Start of block

:1 #Label to jump to if end of file

;$!x # If not the last line switch in the hold buffer we got which doesn't include the next `Start`.

;/5/p # Print if this Start section contains `5`

;x #Switch back hold buffer and pattern to get `Start` back

;s/.*\n// #Delete everything up to last line of pattern buffer(leaving just `Start`.

} # End block

;$!b2 # If not end of file go back to label at the start

;d #Deletes anything left in pattern buffer when we reach the end of the file



输出

Start
5
6
7
8

哪个是正确的

但是将 $!N;$b1; 的顺序更改为 $b1;$!N 会使脚本不输出任何内容。

sed ':2;h;$b1;$!N;/\n.*Start[^\n]*$/{:1;$!x;/5/p;x;s/.*\n//};$!b2;d'

我不知道我是否遗漏了一些明显的东西,或者我没有真正理解 $ 的含义,但在我看来这应该没有什么区别,因为一个命令只执行在最后一行 ($) 和其他所有行,所以顺序应该无关紧要吧?

欢迎任何解释,如果需要更多信息,请告诉我。

此外,我不想要更好的方法,我只想解释为什么会发生这种情况。


更多信息

  • GNU sed 版本 4.1.5

最佳答案

$!N;$b1 在 last 之前的行首先附加,然后分支(因为它现在是最后一行),wheras $b1;$!N不分支,追加,不进入 block 。接下来是 $!b2 未被采用,随后是 d 删除模式。 (并结束脚本,因为没有更多输入)– Hasturkun

关于linux - sed 命令的排序因未知原因而中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32846315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com