Issue
Problem:
- I have a folder (
Essays
) containing many nested sub-directories and ".txt
" files. - Only some files within this folder contain the string '
[[RepeatedPara]]
' somewhere among the content. - Outside the folder I have another text file
specialPara.txt
which contains the paragraph that needs to replace[[RepeatedPara]]
string in all the files. - I have created a script file "
addPara.sh
" which should first copy the contents ofEssays
into new folderEssaysCopy
and then perform the replacement of string with contents ofspecialPara.txt
.
Folder Structure
.
└── WorkingDir/
├── addPara.sh
├── specialPara.txt
├── EssaysCopy
└── Essays/
├── file-01.txt
├── file-02.txt
├── file-03.txt
├── subDir-01/
│ ├── file-01-01.txt
│ ├── file-01-02.txt
│ └── subSubDir-01-01/
│ └── file-01-01.txt
└── subDir-02/
├── file-02-01.txt
└── file-02-02.txt
Script I have so far:
After looking into an answer at stackoverflow I created the following script.
#!/bin/sh
cp -r Essays EssaysCopy
cd EssaysCopy
for FILE in $(find *.txt -type f);
do
sed -i -e '/RepeatedPara/{r ../specialPara.txt' -e 'd' -e '}' $FILE
done
Result:
The above script does replace the line containing the string RepeatedPara
in all files of folder EssaysCopy
but doesn't process the files within the nested sub-directories.
Script I use for creating nested Directories and files for testing:
#!/bin/sh
mkdir Essays
cd Essays
for i in {1..3}
do
mkdir subDir-$i
cd subDir-$i
for j in {1..2}
do
mkdir subDir-$j
cd subDir-$j
for k in {1..2}
do
echo "Some Content at the begining" > file-$i-$j-$k.txt
echo "[[RepeatedPara]]" >> file-$i-$j-$k.txt
echo "Some Content at the End" >> file-$i-$j-$k.txt
done
cd ..
done
for l in {1..2}
do
echo "Some Content at the begining" > file-$i-$l.txt
echo "[[RepeatedPara]]" >> file-$i-$l.txt
echo "Some Content at the End" >> file-$i-$l.txt
done
cd ..
done
for m in {1..2}
do
echo "Some Content at the begining" > file-$m.txt
echo "[[RepeatedPara]]" >> file-$m.txt
echo "Some Content at the End" >> file-$m.txt
done
cd ..
Solution
If it's a bash
script, use a bash
shebang.
Then should use find's -exec
and quote the glob expression:
#!/bin/bash
cp -r Essays EssaysCopy
cd EssaysCopy
find . -type f -name "*.txt" -exec \
sed -i -e '/RepeatedPara/{r ../specialPara.txt' -e 'd' -e '}' {} \;
assuming, as you mentioned that your sed
command works as expected.
Answered By - Diego Torres Milano Answer Checked By - Candace Johnson (WPSolving Volunteer)