Skip to main content

Recursively edit files based on parent directory's name [Resolved]

I have a large directory with hundreds of folders, all following the naming scheme "a_b_x", with x being a random word. In every one of these folders there are 3 text files, all with a couple of strings containing "a_b_x" as well.

I'm trying to rename all of the directories and change the strings inside the files from "a_b_x" to "a_x", meaning the "b_" is supposed to be removed. I hope to accomplish this with some sed wizardry, as manually editing all of the files would take several hours.


Question Credit: naosia
Question Reference
Asked April 5, 2019
Posted Under: Unix Linux
38 views
3 Answers

You should always avoid parsing the output of ls. Try this (thanks to stephane-chazelas for suggesting ./*/):

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

credit: Community
Answered April 5, 2019

Here you are

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

Rename directories:

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

Edit files:

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

Remove backups if all ok:

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

credit: artyom
Answered April 5, 2019
Your Answer