0

My question is how can I change one word in many txt files in one directory and multiple subdirectories in BASH? I did as below (check all similar topics) but it is still not working. changePhrase is a name of directory where the subdirectories and files are. Inside that files there is a string that I want to change. I have to make it with a for loop (it's a task). Where is my mistake? Thank you.

#!/bin/bash

for file in changePhrase; do
    if [[ -f $file ]] && [[ -w $file ]]; then
        sed -i -- 's/old/new/g' "$file"
    fi
done
Jeroen
  • 1,162
  • 1
  • 11
  • 22
versaces
  • 137
  • 6
  • Can you show us how you are calling this script? Is changePhrase a list of all of the text files you want to change it in? – Campbell Nov 18 '18 at 20:30
  • @Campbell changePhrase is a name of directory where the subdirectories and files are. Inside that files is a string that I want to change. – versaces Nov 18 '18 at 20:32

3 Answers3

0

you can do

find changePhraseDir -type f -a -writeable|xargs sed -i 's/foo/bar/'
  • -type f -> file
  • -a -> and
  • -writable -> your -w
Kent
  • 181,427
  • 30
  • 222
  • 283
0

I think your code will work if you just add find to the for loop so:

#!/bin/bash

for file in `find changePhrase`; do
    if [[ -f $file ]] && [[ -w $file ]]; then
        sed -i -- 's/old/new/g' "$file"
    fi
done
Campbell
  • 376
  • 2
  • 8
0

If changePhrase is the name of your directory try to append /**{,/*} to it. Using the globbing will make the loop go over all the files.