關於sed的一些經典練習

創建一個測試文件,其內容是:

#

# hello world

    # hi world

 # this is test file

 # id:3:inittab:default


 #hi like his liker

 #hi love his lover

 #hi love his liker





###end of the file


1、刪除測試文件行首的空白符

   sed -n  's#^[[:space:]]##g' test 

   使用小結:

    -n 靜默模式,僅輸出經過command處理過的行

    's#pattern#string#g'其實就是's/pattern/string/g'意思一樣,只是形式上的不同

    s是替換命令,g是s的參數,表明是全局替換

    ^[[:space:]] ^是行首錨定,[[:space:]] 匹配空白字符。參見正則表達式

2、替換測試文件中id:3:inittab:default的數字3替換成5

    sed -i 's#\(id:\)3\(:inittab:default\)#\15\2#g' test 

    使用小結:

    -i 表明在源文件中修改。這個使用需謹慎

    \1,\2 表對第一個分組的引用和對第二個分組的引用。


3、刪除測試文件中空白行

    sed -n 's/^$//g' test

    's/pattern//g' 如果pattern是:^$表明開始即結束,那麼就是匹配空白行

4、刪除測試文件中開頭的#

    sed -n 's/^#//g' test

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章