shell 如何使用bash脚本递归地替换文件夹中所有文件中的字符串与文件夹外的特定文件的内容?

hmae6n7t  于 2023-05-18  发布在  Shell
关注(0)|答案(1)|浏览(252)

问题:

  • 我有一个文件夹(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 ..
djp7away

djp7away1#

如果它是一个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命令按预期工作。

相关问题