1. 程式人生 > >Linux 下用bash shell正則表示式批量處理檔案的應用例項

Linux 下用bash shell正則表示式批量處理檔案的應用例項

程式碼檔案頭有版本資訊,下面一段shell指令碼就是用來收索和更新程式碼頭註釋裡面的斑斑資訊的。

從中可以到shell指令碼中以下幾個小技術點是如何運用的:

1. 利用正則表示式分組匹配指定內容

2. 字串的定位,截斷和拼接處理

3. 指定檔案指定行替換指定內容

#!/bin/sh

#two input parameters:
#$1---folder name
#$2---eco number

if [[ $# -lt 2 ]]; then
  echo "missing command input parameters"
  exit 1
fi

for file in `ls $1/*.[pi]`
do
  exec < $file
  regex='.+(Revision [eE]nd).+'
  x=1
  laststr=''
  beforestr=''
  newversion=''
  isfind='no'

  while read line
  do
    if [[ "$line" =~ $regex ]]; then
      isfind='yes'
      break;
    fi
    let x++
    beforestr=$laststr
    laststr="$line"
  done

  if [[ $isfind != 'yes' ]]; then
    echo "Didn't handle $file"
    continue;
  fi

  regex='Revision/:/s+([0-9|/.]+).+'
  if [[ "$beforestr" != '' ]]; then
    if [[ "$beforestr" =~ $regex ]]; then
      lastversion=${BASH_REMATCH[1]}


      #Generate next version
      while [[ `expr index "$lastversion" .` -ne 0 ]]
      do
        temp=${lastversion:0:`expr index "$lastversion" .`}
        newversion="${newversion}$temp"
        lastversion=${lastversion:`expr index "$lastversion" .`}
      done
      lastversion=`expr $lastversion + 1`
      newversion=${newversion}$lastversion
    fi
  fi

  regexeco='ECO/:/s*(/*[a-z|A-Z|0-9| ]*/*)/s+/*//'
  if [[ "$laststr" != '' ]]; then
    cline="`expr $x - 1`s"
    if [[ "$laststr" =~ $regex ]]; then
      oldversion=${BASH_REMATCH[1]}


      #Replace new version here
      sed -i "$cline/$oldversion/$newversion/g" $file
    fi

    if [[ "$laststr" =~ $regexeco ]]; then
      oldeco=${BASH_REMATCH[1]}
      neweco="*${2}"
      sed -i "$cline/$oldeco/$neweco/" $file
    fi
  fi
done