1. 程式人生 > >shell指令碼採用sed批量修改檔案

shell指令碼採用sed批量修改檔案

轉載自:http://www.furion.info/81.html

週末看《sed 與 awk 第二版》的時候,看到書上有個很好的shell指令碼-runsed,用來批量修改檔案,當然是通過呼叫sed來修改。

原指令碼程式碼如下:

# !/bin/bash

for x

do

echo “editing $x: \c”

if [ “$x” = sedscr ];

then

echo “not editing sedscript!”

elif [ -s $x ];

then

sed -f sedscr $x >/tmp/$x$$

if [ -s /tmp/$x$$ ];

then

if cmp -s $x /tmp/$x$$

then

echo “file not changed: \c”

else

mv $x $x.bak #save original ,just in case

cp /tmp/$x$$ $x

fi

echo “done”

else

echo “Sed produced an empty file \c”

echo “- check your sedscript.”

fi

rm -f /tmp/$x$$

else

echo “original file is empty.”

fi

done

echo “all done”

指令碼的優點不用多說了,可以自動備份原始檔、失敗時候告警(提示empty)等。但也略微有不方便的地方:

1.無法指定sedsrc檔名

2.沒有使用使用幫助

3.沒有良好的引數處理

正好閒著無事,於是使用getopts加上了引數處理、使用幫助等。

#! /bin/bash

#this script is used for modified files by sed program

sedsrc=

files=

help=

#process the arguments

while getopts ‘s:f:h’ opt

do

case $opt in

s) sedsrc=$OPTARG

;;

f) files=${files}’ ‘${OPTARG}

;;

h) help=true

sedsrc=

file=

;;

esac

done

shift $(($OPTIND – 1))

#if got an -h argument ,print Usag end then efileit

if [ $help ];

then

echo “Usage: runsed -s sedcomand_file -f file1 -f file2 -f fileN ”

echo “Usage: runsed -h”

echo “-s, the sed command you want to efileec which store in a file ”

echo “-f, the file you want to process”

echo “-h, print the Usage”

printf “Example:\n”

printf “\t runsed -s sedsrc -f example \n”

exit 1

fi

if [ -z $sedsrc ] || [ -z “$files” ] ;

then

echo “empty sed command or process files !”

exit 1

fi

#process the sed command

for file in $files

do

echo “editing $file: \c”

if [ “$file” = sedscr ];

then

echo “not editing sedscript!”

elif [ -s $file ];

then

sed -f $sedsrc $file >/tmp/$file$$

if [ -s /tmp/$file$$ ];

then

if cmp -s $file /tmp/$file$$

then

echo “file not changed: \c”

else

mv $file $file.bak #save original ,just in case

cp /tmp/$file$$ $file

fi

echo “done”

else

echo “Sed produced an empty file \c”

echo “- check your sedscr file .”

fi

rm -f /tmp/$file$$

else

echo “original file is empty.”

fi

done

echo “all done”

使用了getops去處理引數,如果-s,-f為空,則報錯;同時如果指定了-h引數則列印幫助手冊,而不執行實際的修改操作。

if [ -z $sedsrc ] || [ -z “$files” ] ; 這裡之所以使用”$files”的寫法,因為files可能包含了多個檔案引數,例如files= 1.test 2.test,如果直接使用[ -z $files] 則會報錯:

binary operator expected

因此加上””引起來可以避免報錯。

f) files=${files}’ ‘${OPTARG}  ;這裡採用了累加的形式儲存多個檔案到files變數中去。同時${OPTARG}是getops中 中的變數。

效果如下:

runsed

可以看出當缺少了-f或者-s引數均會報錯,同時如果指定了-h引數則只打印幫助資訊,而不實際執行修改。