1. 程式人生 > >shell指令碼:以一定規律替換某個目錄下某些檔案中的某個字串

shell指令碼:以一定規律替換某個目錄下某些檔案中的某個字串

題目有些繞,看例子:

我要替換/home/zql/replace_string/目錄下的以10,20,30開頭的檔案中的字串中的某些字串

這些檔案中有pv_centos欄位,如圖10_1k中內容擷取如下:


我要把以pv_centos開頭的字串編號,如下圖所示:

這些檔案中還夾雜其他的字串。

具體實現程式碼如下:

#!/bin/bash
FILE=/home/zql/replace_string/
for file in `ls [1,2,3]*`
do
touch ${FILE}${file}.output
#count total number of lines
count=`cat $file |wc -l`
        for i in `seq $count`
        do
        #get only one line and dump it to temp1 to edit
        sed -n ''${i}'p' $file > ${FILE}temp1
        #edit that line and output to temp2
        sed  s/pv_centos./pv_cent${i}/g  ${FILE}temp1 > ${FILE}temp2
        cat  ${FILE}temp2 >>  ${FILE}${file}.output
        done
        mv ${FILE}${file}.output $file

done
rm temp*
exit
轉載請註明出處http://blog.csdn.net/qianlong4526888/article/details/7699011