Frankie Hung Frankie Hung - 28 days ago 10
Bash Question

Recursively process files in a directory in unix

I have made a script (convert.sh) to convert json files in pretty print format. For example,

convert.sh source.json


It will replace the source.json file, overwrite itself with pretty print format.

Content of convert.sh

#!/bin/bash
INFILE=$1
python -m json.tool $INFILE > $INFILE.tmp
mv $INFILE.tmp $INFILE


It works very well for one file. However, I would like to process all files under a directory. e.g.

dir1\file1.json
dir1\file2.json
dir1\subdir\abc.json
dir1\subdir2\def.json
...


Any single line command to do this? I tried

find dir1 | grep .json | xargs convert.sh


but no success. Please kindly help. Thanks a lot!

Answer

Use find to (1) search for file matching some pattern (2) launch your script on each found file:

find dir1 -name "*.json" -exec convert.sh {} \;