How can I change one string in multiple files in few subdirectories? [duplicate]

佐手、 提交于 2019-12-13 05:14:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!