Bash: Strip trailing linebreak from output

人走茶凉 提交于 2019-11-27 17:03:50

If your expected output is a single line, you can simply remove all newline characters from the output. It would not be uncommon to pipe to the 'tr' utility, or to Perl if preferred:

wc -l < log.txt | tr -d '\n'

wc -l < log.txt | perl -pe 'chomp'

You can also use command substitution to remove the trailing newline:

echo -n "$(wc -l < log.txt)"

printf "%s" "$(wc -l < log.txt)"

Please note that I disagree with the OP's decision to choose the accepted answer. I believe one should avoid using 'xargs' where possible. Yes, it's a cool toy. No, you do not need it here.


If your expected output may contain multiple lines, you have another decision to make:

If you want to remove MULTIPLE newline characters from the end of the file, again use cmd substitution:

printf "%s" "$(< log.txt)"

If you want to strictly remove THE LAST newline character from a file, use Perl:

perl -pe 'chomp if eof' log.txt


Note that if you are certain you have a trailing newline character you want to remove, you can use 'head' from GNU coreutils to select everything except the last byte. This should be quite quick:

head -c -1 log.txt

Also, for completeness, you can quickly check where your newline (or other special) characters are in your file using 'cat' and the 'show-all' flag. The dollar sign character will indicate the end of each line:

cat -A log.txt
Satya

One way:

wc -l < log.txt | xargs echo -n
Andrey Taranov

There is also direct support for white space removal in Bash variable substitution:

testvar=$(wc -l < log.txt)
trailing_space_removed=${testvar%%[[:space:]]}
leading_space_removed=${testvar##[[:space:]]}

If you assign its output to a variable, bash automatically strips whitespace:

linecount=`wc -l < log.txt`

printf already crops the trailing newline for you:

$ printf '%s' $(wc -l < log.txt)

Detail:

  • printf will print your content in place of the %s string place holder.
  • If you do not tell it to print a newline (%s\n), it won't.
Rastislav Hasicek

If you want to print output of anything in Bash without end of line, you echo it with the -n switch.

If you have it in a variable already, then echo it with the trailing newline cropped:

    $ testvar=$(wc -l < log.txt)
    $ echo -n $testvar

Or you can do it in one line, instead:

    $ echo -n $(wc -l < log.txt)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!