Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash echo number of lines of file given in a bash variable without the file name

Tags:

bash

wc

I have the following three constructs in a bash script:

NUMOFLINES=$(wc -l $JAVA_TAGS_FILE) echo $NUMOFLINES" lines"  echo $(wc -l $JAVA_TAGS_FILE)" lines"  echo "$(wc -l $JAVA_TAGS_FILE) lines" 

And they both produce identical output when the script is run:

121711 /home/slash/.java_base.tag lines 121711 /home/slash/.java_base.tag lines 121711 /home/slash/.java_base.tag lines 

I.e. the name of the file is also echoed (which I don't want to). Why do these scriplets fail and how should I output a clean:

121711 lines 

?

like image 286
Marcus Junius Brutus Avatar asked Aug 18 '12 21:08

Marcus Junius Brutus


People also ask

How do I count the number of lines in a file?

Using “wc -l” There are several ways to count lines in a file. But one of the easiest and widely used way is to use “wc -l”. The wc utility displays the number of lines, words, and bytes contained in each input file, or standard input (if no file is specified) to the standard output. 1.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


1 Answers

An Example Using Your Own Data

You can avoid having your filename embedded in the NUMOFLINES variable by using redirection from JAVA_TAGS_FILE, rather than passing the filename as an argument to wc. For example:

NUMOFLINES=$(wc -l < "$JAVA_TAGS_FILE") 

Explanation: Use Pipes or Redirection to Avoid Filenames in Output

The wc utility will not print the name of the file in its output if input is taken from a pipe or redirection operator. Consider these various examples:

# wc shows filename when the file is an argument $ wc -l /etc/passwd 41 /etc/passwd  # filename is ignored when piped in on standard input $ cat /etc/passwd | wc -l 41  # unusual redirection, but wc still ignores the filename $ < /etc/passwd wc -l 41  # typical redirection, taking standard input from a file $ wc -l < /etc/passwd 41 

As you can see, the only time wc will print the filename is when its passed as an argument, rather than as data on standard input. In some cases, you may want the filename to be printed, so it's useful to understand when it will be displayed.

like image 190
Todd A. Jacobs Avatar answered Oct 03 '22 15:10

Todd A. Jacobs