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 
2
  • 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? Commented Nov 18, 2018 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. Commented Nov 18, 2018 at 20:32

3 Answers 3

0

you can do

find changePhraseDir -type f -a -writeable|xargs sed -i 's/foo/bar/' 
  • -type f -> file
  • -a -> and
  • -writable -> your -w
Sign up to request clarification or add additional context in comments.

Comments

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 

Comments

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.

2 Comments

how? can you write it, please
changePhrase/**{,/*}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.