简体   繁体   中英

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). 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; . So now holdspace contains the current number, while patspace contains the numbers till now in reverse order. Then H; appends the list of numbers gone through until now to the holdspace , so that the latest numbr always stays on top. Finally, when last line is reached, it is done for one last time, and printed out through $p .

However, the command outputs only the numbers 24 to 1 in reverse order. The first line should be 25, but somehow that line is being skipped.

Can anyone tell me what is the problem with this code?

You're missing one last 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. I would do this:

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

This sed should do:

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

ot this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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