LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   performing arithmatic operations on output of `wc -l` (https://www.linuxquestions.org/questions/linux-newbie-8/performing-arithmatic-operations-on-output-of-%60wc-l%60-4175467572/)

anandg111 06-27-2013 07:08 AM

performing arithmatic operations on output of `wc -l`
 
Hi
I want to perform arithmatic operations on output of `wc -l`.
for example
Code:

user046@sshell ~ $ ls -l
total 0

where "total 0" will increase one line in wc -l
Code:

filecount=`ls -l | wc -l`
here $filecount will be 1 but is should be 0
how to get rid of it ?

Ygrex 06-27-2013 07:10 AM

Code:

$ mktemp -d
/tmp/tmp.Ogy7kjo9jn
$ ls -l /tmp/tmp.Ogy7kjo9jn/
total 0
$ ls -1 /tmp/tmp.Ogy7kjo9jn
$ ls -1 /tmp/tmp.Ogy7kjo9jn | wc -l
0


Ygrex 06-27-2013 07:13 AM

is it for counting files in the directory? then it can be fooled:
Code:

$ mktemp -d
$ touch /tmp/tmp.F1Si9FgHCI/a
$ touch /tmp/tmp.F1Si9FgHCI/$'new\nline'
$ ls -1 /tmp/tmp.F1Si9FgHCI | wc -l
3


Madhu Desai 06-27-2013 07:24 AM

Code:

filecount=$(ls -1 | wc -l)
Counting Files in the Current Directory

grail 06-27-2013 07:45 AM

A simple answer would be, do not process the output of ls ... http://mywiki.wooledge.org/ParsingLs

Instead of correcting the wrong way, maybe identify what you actually want to do and use a better method :)

jpollard 06-27-2013 09:41 AM

Quote:

Originally Posted by Ygrex (Post 4979543)
is it for counting files in the directory? then it can be fooled:
Code:

$ mktemp -d
$ touch /tmp/tmp.F1Si9FgHCI/a
$ touch /tmp/tmp.F1Si9FgHCI/$'new\nline'
$ ls -1 /tmp/tmp.F1Si9FgHCI | wc -l
3


Then use " -lC1b".

The C1 is one column, and drops the "Total..." line. The "b" causes special characters in a file name to be escaped.

David the H. 06-28-2013 10:04 AM

The proper way to count files in a directory is generally with globbing and an array, at least for simple matches.

Code:

shopt -s dotglob nullglob
files=( * )
echo "There are ${files[@]} files in this directory."

In order to catch hidden files you need to set the dotglob shell option first. Setting nullglob is recommended too, if the pattern matches nothing.

However, what this actually counts is all entries in the directory, including subdirectories. If you actually want simple files only, or some other sub-category, it requires a bit of extra effort to filter them out. Usually you have to loop through them and check each one.

Code:

shopt -s dotglob nullglob
unset f files

for f in *; do
    [[ -f $f ]] && files+=( "$f" )
    [[ -f $f ]] && (( files++ ))    #alternate that just increments a counter
done

echo "There are ${files[@]} files in this directory."  #or just "$files" for the alternate version.

The final option is to use find, and count it's output in some way. You'll probably only want to do this if you need very precise matching ability, however.


All times are GMT -5. The time now is 06:48 AM.