Regex的應用
Regex是用來處理字串的一種工具,和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'
執行個體:刪除程式中的注釋的Regex應用 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