Skip to content
Advertisement

How to run a command on file in directory recursively creating a new file in each directory being visited (Bash)?

I have a directory with a few sub-directories.

.
├── alembic
│   └── results.csv
├── bigdata
│   └── results.csv
├── calchipan
│   └── results.csv

I’d like to create a copy of each results.csv file in the same directory named results_cleaned.csv where certain lines will be removed. Each sub-directory is known to contain only a single file, results.csv.

Running this on a single directory works:

find . -name 'results.csv' | xargs grep -v "Pattern" > results_cleaned.csv

However, running the same command on a root, produces just a single results_cleaned.csv file. I understand that I have to specify that I want to create a file in each sub directory individually, how do I do this?

Advertisement

Answer

You can’t use xarg since all values are feed to single grep. It would be better to iterate over each line of find (file names):

find . -name 'results.csv' | while read -r f
do
    grep -v "Pattern" "$f" > "$(dirname "$f")/results_cleaned.csv"
done
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement