How can I change one string in multiple files in f

2019-09-04 12:42发布

This question already has an answer here:

My qeustion is how in BASH I can change one word in many txt files in one directory and few subdirectories? 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 is a string that I want to change. I have to make it with a for loop (it's a task). Where is 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

3条回答
再贱就再见
2楼-- · 2019-09-04 12:48

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.

查看更多
干净又极端
3楼-- · 2019-09-04 12:59

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
查看更多
做个烂人
4楼-- · 2019-09-04 13:03

you can do

find changePhraseDir -type f -a -writeable|xargs sed -i 's/foo/bar/'
  • -type f -> file
  • -a -> and
  • -writable -> your -w
查看更多
登录 后发表回答