Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output number of lines in a text file to screen in Unix [duplicate]

Tags:

bash

unix

Possible Duplicate:
bash echo number of lines of file given in a bash variable

Was wondering how you output the number of lines in a text file to screen and then store it in a variable. I have a file called stats.txt and when I run wc -l stats.txt it outputs 8 stats.txt

I tried doing x = wc -l stats.txt thinking it would store the number only and the rest is just for visual but it does not work :(

Thanks for the help

like image 331
Masterminder Avatar asked Oct 04 '12 16:10

Masterminder


People also ask

How can I count duplicate records in Unix?

The uniq command has a convenient -c option to count the number of occurrences in the input file. This is precisely what we're looking for. However, one thing we must keep in mind is that the uniq command with the -c option works only when duplicated lines are adjacent.

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

wc. The wc command is used to find the number of lines, characters, words, and bytes of a file. To find the number of lines using wc, we add the -l option. This will give us the total number of lines and the name of the file.

How do you display the first 20 lines of a file in Unix?

To look at the first few lines of a file, type head filename, where filename is the name of the file you want to look at, and then press <Enter>. By default, head shows you the first 10 lines of a file. You can change this by typing head -number filename, where number is the number of lines you want to see.

How do you count the number of lines in a text file?

In notepad , you can type Ctrl + g to view current line number. It also at bottom-right corner of status-bar.


1 Answers

There are two POSIX standard syntax for doing this:

x=`cat stats.txt | wc -l`

or

x=$(cat stats.txt | wc -l)

They both run the program and replace the invocation in the script with the standard output of the command, in this case assigning it to the $x variable. However, be aware that both trim ending newlines (this is actually what you want here, but can be dangerous sometimes, when you expect a newline).

Also, the second case can be easily nested (example: $(cat $(ls | head -n 1) | wc -l)). You can also do it with the first case, but it is more complex:

`cat \`ls | head -n 1\` | wc -l`

There are also quotation issues. You can include these expressions inside double-quotes, but with the back-ticks, you must continue quoting inside the command, while using the parenthesis allows you to "start a new quoting" group:

"`echo \"My string\"`"
"$(echo "My string")"

Hope this helps =)

like image 191
Janito Vaqueiro Ferreira Filho Avatar answered Oct 07 '22 01:10

Janito Vaqueiro Ferreira Filho