Home > Back-end >  Can i combine the ls command with -R and a specific type of file (.txt)
Can i combine the ls command with -R and a specific type of file (.txt)

Time:03-29

I just started using bash programming (if its called that way) a week ago for university so im at rock bottom oops...

The task is to search our computer for .pdf, .txt and .docx files and count them.

Im looking for a way to combine the command

ls **.txt | wc -l

with the command

ls -R | wc -l

I tried combinations of the two commands:

ls -R **.txt | wc -l
ls **.txt -R | wc -l

CodePudding user response:

A bash-only solution has already been given, but I'd like to point you at find which is a great tool for this kind of job. For example:

find . -name '*.txt' -or -name '*.pdf' -or -name '*.docx'

CodePudding user response:

To have ** interpreted as any hierarchy of sub-directories you must enable the globstar option: shopt -s globstar. Then, you should ls **/*.txt, not ls **.txt. Note that ls is usually not what you want for scripting. Prefer:

$ shopt -s globstar nullglob
$ files=(**/*.txt)
$ echo "${#files[@]}"
124

The nullglob option is useful in case you have no txt files. Without it **/*.txt would expand as the literal **/*.txt string and you would get a count of 1. While with nullglob enabled it expands as the empty string.

files=(**/*.txt) stores the list of files in an indexed bash array named files. ${#files[@]} expands as the number of elements in array files.

  • Related