简体   繁体   English

sed命令反向打印文件会跳过最后一行

[英]Sed command to reverse print a file skips last line

I am trying to use sed to reverse print a file (I know it can be done in myriads of other ways, like tac , for example). 我正在尝试使用sed反向打印文件(例如,我知道它可以通过多种其他方式完成,例如tac )。 This is what I got so far: 这是我到目前为止所得到的:

sed -n -r '/.+/{x;H;$p}' nums

The file nums contains a number on each line, from 1 to 25. The logic is this, each number is first copied to the holdspace , while the contents of the holdspace are copied to patspace through x; 文件nums包含在每一行的数,为1〜25的逻辑此,每个号码首先被复制到holdspace ,而内容holdspace被复制到patspace通过x; . So now holdspace contains the current number, while patspace contains the numbers till now in reverse order. 因此,现在holdspace包含当前数字,而patspace包含patspace的数字,其顺序相反。 Then H; 然后H; appends the list of numbers gone through until now to the holdspace , so that the latest numbr always stays on top. 将直到现在为止经过的数字列表追加到holdspace ,以便最新的数字始终保持在最前面。 Finally, when last line is reached, it is done for one last time, and printed out through $p . 最后,当到达最后一行时,它最后一次完成,并通过$p打印出来。

However, the command outputs only the numbers 24 to 1 in reverse order. 但是,该命令仅以相反的顺序输出数字24到1。 The first line should be 25, but somehow that line is being skipped. 第一行应该是25,但是不知何故该行被跳过了。

Can anyone tell me what is the problem with this code? 谁能告诉我这段代码是什么问题?

You're missing one last x . 您缺少最后一个x You swap the contents of the last line into the hold space, but you never pull it back out before printing. 您将最后一行的内容交换到保留空间中,但是在打印之前,请不要将其拉回。

sed -n -r -e '/.+/{x;H}' -e '${x;p}'

You also get an extra blank line because you really don't want to do the 'H' on the first line, since that preserves the initial blank contents of the hold space. 您还会得到一个额外的空白行,因为您确实不想在第一行上执行'H',因为这样可以保留保留空间的初始空白内容。 I would do this: 我会这样做:

sed -n -r -e '/.+/x' -e '2,$H' -e '${x;p}' nums

This sed should do: sed应该执行以下操作:

sed '1!G;h;$!d' file

ot this: 这:

sed -n '1!G;h;$p' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM