Acton Acton - 7 months ago 10
Bash Question

shell script to create files based on existing files in a directory

Say my folder is like below

- folder
- file1.json
- file2.json


I need a shell script which will give me this after running:

- folder
- file1.json
- file2.json
- file1.sh
- file2.sh


After getting the file created. I need then fill up file1.sh and file2.sh with content which partially is copied from file1.json and file2.json accordingly.

I could do this line by line in below way, but this is not practical when I have many files.

touch file1.sh
cat somecontent.txt >> file1.sh
cat file1.txt >> file1.sh
cat othercontetn.txt >> file1.sh
touch file2.sh
cat somecontent.txt >> file2.sh
cat file1.txt >> file2.sh
cat othercontetn.txt >> file2.sh


I am looking for a method auto parse the folder and create files based on whatever files inside the folder. Could first assume there are only files inside folder.
But actually in my case, the best solution should work for situation that there are folders inside folder.

Answer

A method auto parse the folder and create files based on whatever files inside the folder.

The following code finds .json and create same content files with {same prefix}.sh

find /folder -name "*.json"  -exec bash -c 'cat "$1" > "${1%.*}.sh"' _ {} \;
Comments