正则表达式的应用
正则表达式是用来处理字串的一种工具,和bash一样重要,是学习linux的人通二脉。 举个例子:grep命令 去你的~/.bashrc 文件中加入alias grep='grep --color=auto',这样你grep是高亮的。
例子1 查网卡信息 dmesg | grep -n -A3 -B2 'eth'
例子2 查文件中的信息 grep -n 'the' test.txt //从刚刚的文件当中取得 the 这个特定字串 grep -vn 'the' test.txt //当该行没有 'the' 这个字串时才显示在萤幕上 grep -in 'the' test.txt //想要取得不论大小写的 the
grep -n 't[ae]st' test.txt // 搜寻 test 或 taste 这两个单字时 grep -n '[^g]oo' test.txt // oo前面不可以是g grep -n '[^a-z]oo' test.txt // oo前面不可以是小写字母 grep -n '^the' test.txt // the在行首 grep -n '^[^a-z]' test.txt // 不是以小写字母为行首的行
grep -n '\.$' test.txt // 以.结尾的行,\相当于转义字符
grep -n '^$' test.txt // 空行
# grep -v '^$' /etc/syslog.conf | grep -v '^#' # 结果仅有 10 行,其中第一个『 -v '^$' 』代表『不要空白行』, # 第二个『 -v '^#' 』代表『不要开头是 # 的那行』喔!
【注意】 那个 ^ 符号,在字节集合符号(括号[])之内与之外是不同的! 在 [] 内代表『反向选择』,在 [] 之外则代表定位在行首的意义! $表示结尾(window下是^M$,而linux下结尾才是$) . (小数点):代表『一定有一个任意字节』的意思; * (星星号):代表『重复前一个字节, 0 到无穷多次』的意思,为组合形态 特别注意:因为 * 代表的是『重复 0 个或多个前面的 RE 字符』的意义, 因此,『o*』代表的是:『拥有空字节或一个 o 以上的字节』 sed 's/要被取代的字串/新的字串/g'
实例:删除程序中的注释的正则表达式应用 rmnodeofcode.sh
#!/bin/bash
#delcomment.sh #function: this shell script delete the comment in c/c++ source file
function del_comment_file() { #delete the comment line begin with '//comment' sed -i "/^[ \t]*\/\//d" $file
#delete the commnet line end with '//comment' sed -i "s/\/\/[^\"]*//" $file
#delete the comment only occupied one line '' sed -i "s/\/\*.*\*\///" $file
#delete the comment that occupied many lines ' sed -i "/^[ \t]*\/\*/,/.*\*\//d" $file
}
function del_comment() { for file in `ls `; do case $file in *.c) del_comment_file ;; *.cpp) del_comment_file ;; *.h) del_comment_file ;; *) if [ -d $file ]; then cd $file del_comment cd .. fi ;; esac done }
DIR=$1
if [ ! -e $DIR ]; then echo "The file or directory does not exist." exit 1; fi
if [ -f $DIR ]; then file=`basename $DIR` if [[ `echo $DIR | grep /` == $DIR ]]; then cd `echo $DIR | sed -e "s/$file//"` del_comment_file else del_comment_file fi
exit 0; fi
if [ -d $DIR ]; then cd $DIR del_comment exit 0; fi
|