问题
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
回答1:
you can do
find changePhraseDir -type f -a -writeable|xargs sed -i 's/foo/bar/'
-type f
-> file-a
-> and-writable
-> your-w
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/53365081/how-can-i-change-one-string-in-multiple-files-in-few-subdirectories