1

Let assume, I need to count every file in directory which ends with o. (for example ab12.14o, 70010340.09o). Which command I need to use?

I tried ls *.o | wc but it doesn't work.

deepblue_86
  • 1,246

2 Answers2

4

Don't use ls.

Use a shell array to store the name of the files ending in o:

files=( *o )

Now do:

echo "${#files[@]}"

to get the number of files.

@steeldriver has made a fair point, if you have no matching file names then the glob pattern will be taken literally. Because of this, even though there is no matching file names you will still get the file count as 1.

To overcome this set the nullglob or failglob shell option:

shopt -s nullglob
shopt -s failglob
heemayl
  • 93,925
4

You probably just need to remove the .from your glob expression - which is causing it to only match files ending in .o rather than o

However, a better way would be to use find:

find . -maxdepth 1 -name '*o' -printf 'x' | wc -c

You can add -type f to limit it to plain files (exclude directories) and remove the -maxdepth 1 if you want to count recursively.

steeldriver
  • 142,475