Linux

根據父目錄的名稱遞歸編輯文件

  • April 6, 2019

我有一個包含數百個文件夾的大目錄,所有文件夾都遵循命名方案“a_b_x”,其中 x 是一個隨機詞。在這些文件夾中的每一個中都有 3 個文本文件,所有文件都包含幾個包含“a_b_x”的字元串。

我正在嘗試重命名所有目錄並將文件中的字元串從“a_b_x”更改為“a_x”,這意味著應該刪除“b_”。我希望通過一些 sed 嚮導來完成此操作,因為手動編輯所有文件需要幾個小時。

您應該始終避免解析ls. 試試這個(感謝stephane-chazelas的建議./*/):

for folder in ./*/; do     
     sed -i 's/_b//g' "$f"/*; mv "$folder" "${folder/_b/}"; 
done

這個給你

root@testbox:~# mkdir test
root@testbox:~# cd test
root@testbox:~/test# mkdir -p a_b_x{1..10} # populate directories
root@testbox:~/test# printf 'a_b_x\na_b_y\nfoo\nbar\n' | \
   tee a_b_x{1..10}/somefile # populate files
a_b_x
a_b_y
foo
bar

重命名目錄:

root@testbox:~/test# find . -name a_b_\* -type d -print0 | \
   xargs -r0 rename -v 's/a_b_/a_/'
./a_b_x10 renamed as ./a_x10
./a_b_x5 renamed as ./a_x5
./a_b_x7 renamed as ./a_x7
./a_b_x4 renamed as ./a_x4
./a_b_x8 renamed as ./a_x8
./a_b_x3 renamed as ./a_x3
./a_b_x9 renamed as ./a_x9
./a_b_x6 renamed as ./a_x6
./a_b_x1 renamed as ./a_x1
./a_b_x2 renamed as ./a_x2

編輯文件:

root@testbox:~/test# find . ! -name \*.bak -type f -print0 | xargs -r0 sed -i.bak 's,a_b_,a_,'
root@testbox:~/test# cat a_x4/somefile
a_x
a_y
foo
bar

如果一切正常,請刪除備份:

root@vm8583:~/test# find . -name \*.bak -type f -delete

引用自:https://unix.stackexchange.com/questions/65298