Answering How to remove the last CR char with cut
I found out that some programs do add a trailing new line to the end of a string, while others don't:
Say we have the string foobar
and print it with printf
so that we don't get an extra new line:
$ printf "foobar" | od -c
0000000 f o o b a r
0000006
Or with echo -n
:
$ echo -n "foobar" | od -c
0000000 f o o b a r
0000006
(echo
's default behaviour is to return the output followed by a newline, so echo "foobar"
returns f o o b a r
).
Neither sed
nor cat
do add any extra character:
$ printf "foobar" | sed 's/./&/g' | od -c
0000000 f o o b a r
0000006
$ printf "foobar" | cat - | od -c
0000000 f o o b a r
0000006
Whereas both awk
and cut
do. Also xargs
and paste
add this trailing new line:
$ printf "foobar" | cut -b1- | od -c
0000000 f o o b a r
0000007
$ printf "foobar" | awk '1' | od -c
0000000 f o o b a r
0000007
$ printf "foobar" | xargs | od -c
0000000 f o o b a r
0000007
$ printf "foobar" | paste | od -c
0000000 f o o b a r
0000007
So I was wondering: why is this different behaviour? Is there anything POSIX suggests about this?
Note I am running all of this in my Bash 4.3.11 and the rest is:
- GNU Awk 4.0.1
- sed (GNU sed) 4.2.2
- cat (GNU coreutils) 8.21
- cut (GNU coreutils) 8.21
- xargs (GNU findutils) 4.4.2
- paste (GNU coreutils) 8.21
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…