0

I have to make a script that will be changing one string with different word in the current directory and all subdirectories in this current directory. I want to replace name Leo with Leonidas in all files in directory and all files in subdirectories.

I have two questions:

  1. Why this script is not changing string in files in subdirectories?

  2. Why this script can be executed only once? When I try to run it for the second time, it's not working.

    #!/bin/bash
    
    for file in *; do
    if [[ -f $file ]] && [[ -w $file ]]; then
        sed -i -- 's/Leo/Leonidas/g' "$file"
    fi
    done
    
Community
  • 1
  • 1
versaces
  • 137
  • 6
  • `*` will not expand directories, try substituting `*` with something like `$(find . -type f)`. – ssemilla Nov 19 '18 at 15:00
  • Same question asked yesterday: https://stackoverflow.com/questions/53365081/how-can-i-change-one-string-in-multiple-files-in-few-subdirectories – Campbell Nov 19 '18 at 15:24

1 Answers1

0

Why this script is not changing string in files in subdirectories?

As mentioned in my comment, * does not expand subdirectories. You can use something like find to search subdirectories.

#!/bin/bash

targetdir="$1" # set this to the directory of files you want to change

for file in $(find "$targetdir" -type f); do
    if [[ -f $file ]] && [[ -w $file ]]; then
        sed -i -- 's/Leo/Leonidas/g' "$file"
    fi
done

Why this script can be executed only once? When I try to run it for the second time, it's not working.

Because you are running it in the same directory as the files you are updating with sed. Hence, even your script will be updated by sed because it contains the word Leo in the line sed -i -- 's/Leo.... Your script must not be in the same directory with the files you are trying to update.

By the way, you can achieve the same effect without a script:

find . -type f -writable | xargs -i sed -i 's/Leo/Leonidas/g' {}
ssemilla
  • 3,900
  • 12
  • 28