问题:
- 我有一个文件夹(
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
结果:
上面的脚本确实替换了EssaysCopy
文件夹所有文件中包含字符串RepeatedPara
的行,但不处理嵌套子目录中的文件。
用于创建嵌套目录和测试文件的脚本:
#!/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 ..
1条答案
按热度按时间djp7away1#
如果它是一个
bash
脚本,则使用bash
shebang。然后应该使用find的
-exec
并引用glob表达式:假设,正如你提到的,你的
sed
命令按预期工作。