What is the meaning of :a;$!N; in a sed command?
These are the, admittedly cryptic, sed
commands. Specifically (from man sed
):
: label
Label for b and t commands.t label
If a s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script.n N Read/append the next line of input into the pattern space.
So, the script you posted can be broken down into (spaces added for readbility):
sed ':a; $!N; s/\n/string/; ta'
--- ---- ------------- --
| | | |--> go back (`t`) to `a`
| | |-------------> substitute newlines with `string`
| |----------------------> If this is not the last line (`$!`), append the
| next line to the pattern space.
|----------------------------> Create the label `a`.
Basically, what this is doing could be written in pseudocode as
while (not end of line){
append current line to this one and replace \n with 'string'
}
You can understand this a bit better with a more complex input example:
$ printf "line1\nline2\nline3\nline4\nline5\n" | sed ':a;$!N;s/\n/string/;ta'
line1stringline2stringline3stringline4stringline5
I am not really sure why the !$
is needed. As far as I can tell, you can get the same output with
printf "line1\nline2\nline3\nline4\nline5\n" | sed ':a;N;s/\n/string/;ta'