Bash – How to delete a trailing newline in bash

bashnewlinesshell-scripttext processing

I'm looking for something that behaves like Perl's chomp. I'm looking for a command that simply prints its input, minus the last character if it's a newline:

$ printf "one\ntwo\n" | COMMAND_IM_LOOKING_FOR ; echo " done"
one
two done
$ printf "one\ntwo" | COMMAND_IM_LOOKING_FOR ; echo " done"
one
two done

(Command substitution in Bash and Zsh deletes all trailing new lines, but I'm looking for something that deletes one trailing new line at most.)

Best Answer

This should work:

printf "one\ntwo\n" | awk 'NR>1{print PREV} {PREV=$0} END{printf("%s",$0)}' ; echo " done"

The script always prints previous line instead of current, and the last line is treated differently.

What it does in more detail:

  1. NR>1{print PREV} Print previous line (except the first time).
  2. {PREV=$0} Stores current line in PREV variable.
  3. END{printf("%s",$0)} Finally, print last line withtout line break.

Also note this would remove at most one empty line at the end (no support for removing "one\ntwo\n\n\n").

Related Question