bash - sed: replacing end of line -
i need quote end of line , using this solution replace end of line working when file has multiple lines.
problem arises when try use method files have no \n
or have single line ending \n
. in case sed
not replace anything, second s/
command not work. looks last end of line never replaced.
my command is:
sed ':a;n;$!ba;s/\n/\\n/g;s/a/_/g' <file>
(replace \n
\\n
, replace a
_
example).
i use hexdump -c
display files here:
there tests made:
$ # test1. single line without \n $ echo -n 'abc' | sed ':a;n;$!ba;s/\n/\\n/g;s/a/_/g' | hexdump -c 00000000 61 62 63 |abc| # expected "_bc" $ # test2. single line \n $ echo 'abc' | sed ':a;n;$!ba;s/\n/\\n/g;s/a/_/g' | hexdump -c 00000000 61 62 63 0a |abc.| # expected "_bc\n" $ # test3. 2 lines $ echo -e 'abc\n' | sed ':a;n;$!ba;s/\n/\\n/g;s/a/_/g' | hexdump -c 00000000 5f 62 63 5c 6e 0a |_bc\n.| # expected "_bc\n\n"
questions: why second s/
not replace in test1 , test2? there method fix replacing of s/\n/\\n/
, s/a/_/g
in tests?
p.s.: don't want workaround adding newline @ end of stream before sed processing , removing after.
edit: looks n
command not read single line, if followed '\n'. idea how fix it?
edit2: seems expected behavior of n
command. there method on how replace last line ending?
this might work (gnu sed):
sed ':a;$!{n;ba};s/\n/\\n/g;s/a/_/g' file
or:
sed ':a;$!n;$!ba;s/\n/\\n/g;y/a/_/' file
logically makes sense: 1 cannot next
line if on last
line.
Comments
Post a Comment