Reputation: 12108
I have this dir structure:
ParentDir
|
-- Child Dir1
|
-- File One.txt
-- File
|
-- Child Dir2
|
-- File Two.txt
-- File
I'm trying to find out all the .txt
files and count the sum total of number of lines in them, so I do something like this:
TXTFILES=$(find . -name '*.txt')
cat $TXTFILES | wc -l
but the problem is, I get,
cat: ./Child: No such file or directory
cat: Dir2/File: No such file or directory
cat: Two.txt: No such file or directory
cat: ./Child: No such file or directory
cat: Dir1/File: No such file or directory
cat: One.txt: No such file or directory
How do I handle spaces in the Dir & File names in such a situation? Is it possible without using a loop?
Upvotes: 0
Views: 944
Reputation: 612
You can surround your files name path by " " like this
find . -name '*.txt' | sed -e 's/^/"/g' -e 's/$/"/g' | wc -l
Example :
prompt$ touch a.txt "a a.txt"
prompt$ find . -name '*.txt' | sed -e 's/^/"/g' -e 's/$/"/g'
"./a a.txt"
"./a.txt"
prompt$ find . -name '*.txt' | sed -e 's/^/"/g' -e 's/$/"/g' | wc -l
2
Upvotes: 0
Reputation: 25438
find . -name '*.txt' -exec cat -- '{}' ';' | wc -l
This runs cat
individually for each file (which is less than ideal), but the filename is passed directly from find
to cat
without being parsed by the shell. So the filename could be anything that's problematic on the command line.
Upvotes: 3
Reputation: 27568
If you don't need to store the file names in a variable, you can do this in 1 line:
find . -name '*.txt' -print0 | xargs -0 wc -l
find
supports a -print0
option that makes it use a null byte, rather than a space, to separate the file names. xargs
supports a -0
(hyphen zero) switch to tell it the incoming file names are separated by a null byte rather than a space.
Upvotes: 4