Essays
)包含许多嵌套的子目录和“.txt
”文件。[[RepeatedPara]]
'。specialPara.txt
,其中包含需要替换所有文件中的[[RepeatedPara]]
字符串的段落。addPara.sh
”,它应该首先将Essays
的内容复制到新文件夹EssaysCopy
中,然后用specialPara.txt
的内容执行字符串替换。.
└── 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
在 stackoverflow 上查看答案后,我创建了以下脚本。
#!/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
上面的脚本确实替换了文件夹
RepeatedPara
的所有文件中包含字符串EssaysCopy
的行,但不处理嵌套子目录中的文件。
#!/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 ..
如果是
bash
脚本,请使用 bash
shebang.
然后应该使用find的
-exec
并引用glob表达式:
#!/bin/bash
cp -r Essays EssaysCopy
cd EssaysCopy
find . -type f -name "*.txt" -exec \
sed -i -e '/RepeatedPara/{r ../specialPara.txt' -e 'd' -e '}' {} \;
假设,正如您提到的那样,您的
sed
命令按预期工作。