1. 程式人生 > >linux 批量替換檔案內容及查詢某目錄下所有包含某字串的檔案(批量修改檔案內容)

linux 批量替換檔案內容及查詢某目錄下所有包含某字串的檔案(批量修改檔案內容)

sed replace word / string syntax

The syntax is as follows:

C程式碼  收藏程式碼
  1. sed -i 's/old-word/new-word/g' *.txt  

GNU sed command can edit files in place (makes backup if extension supplied) using the -i option. If you are using an old UNIX sed command version try the following syntax:

C程式碼  收藏程式碼
  1. sed 's/old/new/g'
     input.txt > output.txt  

You can use old sed syntax along with bash for loop:

C程式碼  收藏程式碼
  1. #!/bin/bash  
  2. OLD="xyz"  
  3. NEW="abc"  
  4. DPATH="/home/you/foo/*.txt"  
  5. BPATH="/home/you/bakup/foo"  
  6. TFILE="/tmp/out.tmp.$$"  
  7. [ ! -d $BPATH ] && mkdir -p $BPATH || :  
  8. for f in $DPATH  
  9. do  
  10.   if [ -f $f -a -r $f ]; then  
  11.     /bin/cp -f $f $BPATH  
  12.    sed "s/$OLD/$NEW/g" "$f" > $TFILE && mv $TFILE "$f"  
  13.   else  
  14.    echo "Error: Cannot read $f"  
  15.   fi  
  16. done  
  17. /bin/rm $TFILE  

A Note About Bash Escape Character

A non-quoted backslash \ is the Bash escape character. It preserves the literal value of the next character that follows, with the exception of newline. If a \newline pair appears, and the backslash itself is not quoted, the \newline is treated as a line continuation (that is, it is removed from the input stream and effectively ignored). This is useful when you would like to deal with UNIX paths. In this example, the sed command is used to replace UNIX path "/nfs/apache/logs/rawlogs/access.log" with "__DOMAIN_LOG_FILE__":

C程式碼  收藏程式碼
  1. #!/bin/bash  
  2. ## Our path  
  3. _r1="/nfs/apache/logs/rawlogs/access.log"  
  4. ## Escape path for sed using bash find and replace   
  5. _r1="${_r1//\//\\/}"  
  6. # replace __DOMAIN_LOG_FILE__ in our sample.awstats.conf  
  7. sed -e "s/__DOMAIN_LOG_FILE__/${_r1}/" /nfs/conf/awstats/sample.awstats.conf  > /nfs/apache/logs/awstats/awstats.conf  
  8. # call awstats  
  9. /usr/bin/awstats -c /nfs/apache/logs/awstats/awstats.conf  

The $_r1 is escaped using bash find and replace parameter substitution syntax to replace each occurrence of /with \/.

perl -pie Syntax For Find and Replace

The syntax is as follows:

C程式碼  收藏程式碼
  1. perl -pie 's/old-word/new-word/g' input.file > new.output.file