Bash: Strip trailing linebreak from output

2019-01-12 19:07发布

When I execute commands in Bash (or to be specific, wc -l < log.txt), the output contains a linebreak after it. How do I get rid of it?

6条回答
贪生不怕死
2楼-- · 2019-01-12 19:21

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
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-12 19:27

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:]]}
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-12 19:31

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

linecount=`wc -l < log.txt`
查看更多
对你真心纯属浪费
5楼-- · 2019-01-12 19:34

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.
查看更多
Root(大扎)
6楼-- · 2019-01-12 19:39

One way:

wc -l < log.txt | xargs echo -n
查看更多
放荡不羁爱自由
7楼-- · 2019-01-12 19:44

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)
查看更多
登录 后发表回答