find and replace string in a file

纵然是瞬间 提交于 2019-12-18 19:07:58

问题


I'm trying to find and replace a string in a folder of files.

Could someone possibly help me?

My script is as follows:

#!/bin/bash
OLD="This is a"
NEW="I am a"
DPATH="/home/user/test/*.txt"
BPATH="/home/user/test/backup/foo"
[ ! -d $BPATH ] && mkdir -p $BPATH || :
for f in $DPATH
do
  if [ -f $f -a -r $f ]; then
    /bin/cp -f $f $BPATH
    sed "s/$OLD/$NEW/g" "$f"
   else
    echo "Error: Cannot read $f"
  fi
done

Now this seems to find the string 'This is a' and replaces with 'I am a', but this only prints to screen.

I need it to replace in the files themselves.

Thanks


回答1:


Use the -i option of sed to make the changes in place:

sed -i "s/$OLD/$NEW/g" "$f"
    ^^



回答2:


The output goes to screen (stdout) because of the following:

sed "s/$OLD/$NEW/g" "$f"

Try redirecting to a file (the following redirects to a new files and then renames it to overwrite the original file):

sed "s/$OLD/$NEW/g" "$f" > "$f.new" && mv "$f.new" "$f"



回答3:


this is a snippet i use, it removes all stuff between APA and BEPA (across multiple lines, including removing APA, BEPA) in all files below current directory, exclude the .svn directory

find . \! -path '*.svn*' -type f -exec sed -i -n '1h;1!H;${;g;s/APA[ \t\r\n]*BEPA//g;p}' {} \;



回答4:


Check this out

http://cs.boisestate.edu/~amit/teaching/handouts/cs-unix/node130.html

##########################################################
\#!/bin/sh

\# sed/changeword

prog=`basename $0`

case $# in
0|1) echo 'Usage:' $prog '<old string> <new string>'; exit 1;;
esac

old=$1
new=$2
for f in *
do
        if test "$f" != "$prog"

        then
            if test -f "$f"
            then
                sed "s/$old/$new/g" $f > $f.new
                mv $f $f.orig
                mv $f.new $f
                echo $f done
            fi
        fi
done

##############################################################


来源:https://stackoverflow.com/questions/4437901/find-and-replace-string-in-a-file

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