find and replace string in a file

前端 未结 4 1939
天命终不由人
天命终不由人 2021-01-04 02:25

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=\"Thi         


        
相关标签:
4条回答
  • 2021-01-04 02:54

    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
    
    ##############################################################
    
    0 讨论(0)
  • 2021-01-04 03:09

    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"
    
    0 讨论(0)
  • 2021-01-04 03:10

    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}' {} \;
    
    0 讨论(0)
  • 2021-01-04 03:12

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

    sed -i "s/$OLD/$NEW/g" "$f"
        ^^
    
    0 讨论(0)
提交回复
热议问题