Reputation: 65
I have a list of directories in a text file, wherein I want to find and change files that share a particular naming convention.
example file:
dir1
dir2
dir3
example folder structure with files
dir1/
thing.txt
thing.blah
dir2/
rar.txt
thing.blah
dir3/
apple.txt
another.text.file.txt
thing.blah
First, I find the name of the .txt, but then I want to perform a change on it. For example, i want to perform a sed command on thing.txt, rar.txt and apple.txt, but not another.text.file.txt.
My question is, once I have all the file names, how do I perform a command on the files with those names? How can I then take those lines of text such as:
cat dirFile.txt | xargs ls | grep <expression>.txt
thing.txt
rar.txt
apple.txt
!cat | some command
and run an action on the actual files under the directories?
What I'm getting is the above result,
But what I need is
dir1/thing.txt
dir2/rar.txt
dir3/apple.txt
Upvotes: 0
Views: 5880
Reputation: 1925
Say you have a file named dirs
which have all directories you need to search:
while IFS= read -r i; do
find "$i" -name '<expression>' -print0
done < dirs | xargs -0 some_command
If you know the directories doesn't have spaces or another type of separators you can simplify a bit:
find $(<dirs) -name '<expression>' -print0 | xargs -0 some_command
Perhaps your some_command
expect only one file at a time, in this case use -n1
:
... | xargs -0 -n1 some_command
or move some_command
to find itself:
find $(<dirs) -name '<expression>' -exec some_command {} \;
$(<dirs)
is a comand substitution. It reads the content (like cat
) of dirs
file and use it as the first arguments of find
. Empty dirs
is safe on GNU find (eg Linux) but you need at least one line - which is converted as one argument - on BSD (eg Mac OS X)-print0
separates files with null
-0
expects these null
chars.-n1
says xargs
to send only one argument to some_command
Upvotes: 2
Reputation: 204
I guess my comments were not adequately expressed. to get the output you desire;
cat dirfile.txt | xargs -I % find % -name <your file spec> or -regex <exp>
Upvotes: 1