Interesting Trick with BASH
Also works with DASH
There is a way to get rid of the last, and only the last, newline in a file, if it exists. xxd
, in case you don't use it often, reads stdin
and shows you what was read, in hex.
printf "one\ntwo\nthree\n" > test.txt
cat test.txt | xxd
00000000: 6f6e 650a 7477 6f0a 7468 7265 650a one.two.three.
printf "%s" "$(cat test.txt)" | xxd
00000000: 6f6e 650a 7477 6f0a 7468 7265 65 one.two.three
This won't work with DOS-style newlines (\r\n
). The last \r
won't be eliminated. That would need a tr -d "\r"
, but that would eliminate all the \r
s.
If you knew for certain that there was a newline at the end, you could measure the length of the file with wc -c
and use head -c
to eliminate it. But this trick is so simple, I think I'd use it anyway with BASH and DASH.
I don't know if this trick works with any shells other than BASH and DASH. I think printf
is always a built-in command, so it would depend on the shell.
BTW, DASH is the variant form of BASH that Debian and Debian derivatives use. With Mint, commands you type from the command line, by default, use BASH, but scripts, by default, use DASH. This matters because echo
works slightly different with DASH and BASH. That's why some people use printf "%s\n" "whatever"
instead of echo "whatever"
in scripts.
#newline #newlines #bash #dash #shell #shell-script #trick #hack #programming #coding