linuxRegex簡介

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.