Bash: separator line with line output

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

+159
bash newline line-breaks
Sep 21
source share
6 answers

If your expected result is one line , you can simply remove all newline characters from the output. It would be no coincidence to connect to the tr utility or to Perl if necessary:

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

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

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

Please note that I do not agree with the OP's decision to select the accepted answer. I believe that the use of β€œhargs” should be avoided where possible. Yes, this is a cool toy. No, you don’t need it here.




If your expected output may contain multiple lines , then you have another solution:

If you want to remove the MULTIPLE newlines from the end of the file, use the cmd replacement again:

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

If you want to strictly remove the LAST character of the newline from the file, use Perl:

 perl -pe 'chomp if eof' log.txt 






Note: if you are sure that you have a trailing newline that you want to remove, you can use the "head" from GNU coreutils to select everything except the last byte. This should be pretty fast:

 head -c -1 log.txt 

In addition, for completeness, you can quickly check where your newlines (or other special characters) are in your file using "cat" and the "show-all" flag. A dollar sign will indicate the end of each line:

 cat -A log.txt 
+204
Sep 21
source share

One of the methods:

 wc -l < log.txt | xargs echo -n 
+87
Sep 21
source share

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

 testvar=$(wc -l < log.txt) trailing_space_removed=${testvar%%[[:space:]]} leading_space_removed=${testvar##[[:space:]]} 
+12
Nov 08 '13 at 11:27
source share

If you assign your output to a variable, bash automatically separates spaces:

 linecount=`wc -l < log.txt` 
+9
Sep 21 '12 at 4:40
source share

printf is already trimming the final newline for you:

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

More details:

  • printf will print your content instead of the %s line holder.
  • If you do not tell him to print a new line ( %s\n ), it will not.
+9
Sep 21 '12 at 22:32
source share

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

If you have this in the variable already, then echoing it with the ending new line is truncated:

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

Or you can do it on one line, instead:

  $ echo -n $(wc -l < log.txt) 
+5
Sep 21 '12 at 7:25
source share



All Articles