Jin
Jin

Reputation: 555

Find and execute command on all files in directory that have a specific folder name

I want to use the find command to execute a special command on all of the files inside the directory that are contained inside multiple different directories with a specific keyword in it (the keyword is "Alpha") and keep the output inside the working directory of the initial file I ran the command on.

The command works such that it requires to you to provide the initial file to perform the command on and then the name of the newly converted file. So like this

command file_to_run_command_on.txt new_file.txt

This is my code

find $PWD -name *.txt* -exec command {} new_file. \;

Right now, it finds all the text files in this directory even in the sub directories and outputs just one file in the directory I run the initial find command from. I'm also unsure how to add the additional search for the keyword in the directory. All advice appreciated!

Upvotes: 3

Views: 2959

Answers (1)

that other guy
that other guy

Reputation: 123650

-exec runs the command in the directory from which you start find.

-execdir runs the command in the matching file's directory.

To only find *.txt* files whose parents contain a specific file, you could use:

find "$PWD" -path "*keyword*/*.txt*" -execdir command {} new_file \;

This will run the command for foo/bar/some-keyword-dir/baz/etc/file.txts but not for foo/bar/baz/file.txts (no keyword in parent directory names) or foo/bar/some-keyword-dir/baz/file.tar (not *.txt*)

Upvotes: 7

Related Questions