Reputation: 135
I stumble upon the command sed -e 's/ /\'$'\n/g'
that supposedly takes an input and split all spaces into new lines. Still, I don't quite get how the '$'
works in the command. I know that s
stands for substitute, / /
stands for the blank spac, \n
stands for new line and /g
is for global replacement, but not sure how \'$'
fits in the picture. Anybody who can shed some light here will be much appreciated.
Upvotes: 3
Views: 359
Reputation: 158060
Basically it's meant for platform portability. With GNU sed it would be just
sed -e 's/ /\n/g'
because GNU sed is able to interpret \n
as new line.
However, other versions of sed, like the BSD version (that comes with MacOS) do not interprete \n
as newline.
That's why the command is build out of two parts
sed -e 's/ /\' part2: $'\n/g'
The $'\n/g'
is an ANSI C string parsed by the shell before executing sed. Escape sequences like \n
will get expanded in such strings. Doing so, the author of the command passed a literal new line (0xa
) to the sed command rather than passing the escape sequence \n
. (0x5c 0x6e
).
One more thing, since the newline (0xa
) is a command separator in sed, it needs to get escaped. That's why the \ at the end of the first part.
Alternatively you could just use a multiline version:
sed -e 's/ /\
/g'
Btw, I would have written the command like
sed -e 's/ /\'$'\n''/g'
meaning just putting the $'\n'
into the ANSI C string. Imo that's better to understand.
Upvotes: 5