[sed] sed 技巧记录

来源:互联网 发布:胡歌车祸知乎 编辑:程序博客网 时间:2024/05/18 16:15

写了一个脚本,用sed来规范化源码的书写格式。

其中还遇到不少值得注意的问题。


1.  \s在[ ] 中不会被认为是空白字符。而是认为"\" 与"s"两个字符。

但是在外面,则能正常代表空白字符。


if [ $# -eq 0 ]
then
echo "ERROR: you should specify the file name"
echo "Usage: format_code file_name"
exit
elif [ $# -gt 1 ]
then
echo "ERROR: can't support two file name. Later multi file will be supported"
echo "Usage: format_code file_name"
exit
fi


if [ ! -f $1 ]
then
echo "ERROR: $1 is not exist!! Please check file name!"
exit
fi


## backup the original file
alias cp=cp
cp -f $1 $1.bak


##1. add space between if and (). \b is needed becauseof excluding $1 function definition like testif()
sed -i 's#\bif(#if (#g' $1


##2. delete space appending $1 line
sed -i 's#\s\+$##g' $1


##3. delete space in front of line(^\t$ is ok but we still delete it)
sed -i 's#^\s\+$##g' $1


##4. two parameter separated by ",". No space before "," and a space after ","
sed -i 's#\(\w\)\s\+,#\1,#g' $1
sed -i 's#,\(\w\)#, \1#g' $1


##5. pointer: "*" must before name and have a space after type name (e.g $1. int *p, not int* p)
sed -i 's#\(\w\)\*#\1 \*#g' $1


##6. add space between ) and {

sed -i 's#){#) {#g' $1



##7. 在目标字符串后插入一行string,且该string前面有空格

sed -i "/storm.zookeeper.servers/a \     \- \"slave$i\"" $WORKDIR/storm_conf/storm.yaml


0 0