Timeline for How does the command sed '1!G;h;$!d' reverse the contents of a file?
Current License: CC BY-SA 3.0
14 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Oct 1, 2015 at 7:14 | comment | added | Scott - Слава Україні | (1) The OP’s sub-question/observation (in the comment) is, “so the h command on the last line is sort-of a no-op.” (with added emphasis, and slightly paraphrased). He’s right; when sed is processing the last line of input, the G reads the hold space (in order to append it to the pattern space), and then the h copies the pattern space to the hold space, which is never referenced again. We could just as well say sed 'G;$!h;$!d' or sed 'G;$!{h;d}'. (2) We could avoid using d by saying sed -n 'G;h;$p'. | |
| Oct 1, 2015 at 7:09 | history | edited | Scott - Слава Україні | CC BY-SA 3.0 | Tweaked formatting, grammar, spelling, punctuation, etc.; tried to add some clarification. |
| Oct 1, 2015 at 0:01 | history | edited | terdon♦ | CC BY-SA 3.0 | typo |
| Sep 30, 2015 at 19:54 | comment | added | chaos | @user1717828 If we wouldn't the first line would be printed, when processed. Since sed is not invoked with -n we have to delete every line except the last. At the last line sed appends everything from the hold space to the pattern space. And because the d command will not be executed, the line is printed (this line contains now the whole file reversed). | |
| Sep 30, 2015 at 19:29 | comment | added | user1717828 | In step 1, why do we have to delete the line from the pattern space at the end? Doesn't this happen as soon as we get to the next line? | |
| S Sep 30, 2015 at 14:48 | history | suggested | T.J. Crowder | CC BY-SA 3.0 | fix typo at end and a few other minor things |
| Sep 30, 2015 at 14:47 | review | Suggested edits | |||
| S Sep 30, 2015 at 14:48 | |||||
| Sep 30, 2015 at 14:44 | comment | added | chaos | @Geek In sed there is only one hold space. It's like a variable which can contain something. | |
| Sep 30, 2015 at 14:41 | comment | added | Geek | Can we think of the hold space like registers for vim? Are they also numbered? Or there is only one of them? | |
| Sep 30, 2015 at 14:39 | history | edited | chaos | CC BY-SA 3.0 | added 63 characters in body |
| Sep 30, 2015 at 14:39 | vote | accept | Geek | ||
| Sep 30, 2015 at 14:38 | comment | added | chaos | @Geek No, the h command copies the pattern space to the hold space, which persist until sed ends. After the end of the script everything is cleared, because the binary exited. | |
| Sep 30, 2015 at 14:35 | comment | added | Geek | so the h command on the last line is sort of no-op. Does it clear itself after the end of the script? | |
| Sep 30, 2015 at 14:15 | history | answered | chaos | CC BY-SA 3.0 |