----------------------------------------------------------------------------------------------------------------------------
**********************
2017-1-13:初版
**********************
小記:用MAC工作已經三周,本以為已經完全了解MAC與Windows的各種不同,沒想到這兩天被Shell給擺了一道,mac下的shell和linux下竟然有些許的不同,由此耽誤了我3個小時的寶貴時間,特此吐槽,做個整理。
------------------------------------------------------------------------------------------------------------------------------
對於shell小白的我,先看這里比較詳細的sed簡明教程,針對linux的用法。
MAC和Linux的區別,參考網址:
http://blog.csdn.net/cbbbc/article/details/50474947
錯誤解決
sed command hits “undefined label” error on Mac OS X
http://www.mkyong.com/mac/sed-command-hits-undefined-label-error-on-mac-os-x/
接下來言歸正傳,步入正題:
原數據
可以用vi或者vim創建一個test.txt的文本,
dongzhengdeMacBook-Pro:temp dongzheng$ vim test.txt
文本內容如下:
dongzhengdeMacBook-Pro:temp dongzheng$ cat test.txt aaaa bbbb cccc dddd
占位符
在匹配行的前一行或者后一行添加內容
寫法:
#匹配行前加 sed -i '/dzblog/inickname' file #匹配行前后 sed -i '/dzblog/athis is my blog address' file
書寫時為了方便區分,往往會在i或者a的后面加一個反斜杠。代碼就變成:
#匹配行前加 sed -i '/dzblog/i\nickname' file #匹配行前后 sed -i '/dzblog/a\this is my blog address' file
想記住也很簡單,a就記憶成after就可以了。
例子:
在第二行即"bbbb"行的下面添加一行,內容為"delon"
Linux命令:
sed '/bbbb/a\delon' test.txt
如果此命令在MAC下輸入,會報錯:
sed: 1: "/bbbb/a\delon": extra characters after \ at the end of a command
占位符
MAC命令:
➜ Home sed '/aaaa/a\ delon ' test.txt
結果:
aaaa
bbbb
delon
cccc
dddd
在某行的前面添加,只需要把'a'換成'i'即可。
此命令不會在原文件上進行更改,只是會把結果輸出到termimal里,如果需要直接更改文件,需要參數 -i
直接替換文件里的指定文本
主要介紹-i和替換文本的方式
Linux命令
#直接將file文件里的printa替換為printb sed -i 's/printa/printb/' test.txt
MAC上的命令當然略有不同,報錯為:
sed: 1: "test.txt": undefined label 'est.txt'
MAC命令:
#mac的使用方式sed -ixxx 's/被替換文本/替換文本/' test.txt sed -i.bak 's/printa/printb/' test.txt
-i后面跟字母數字均可,比如說我寫的-i.bak,這樣的話,會在file的同級目錄下,出現一個test.txt.bak的文件,這個文件備份的是文件修改前的內容。
我想mac的設計初衷或許是為了防止sed改錯的悲劇,所以必須強制備份。
復制過來,未驗證
Linux shell腳本 刪除文件中的一行內容
比如:在1.txt里有以下內容:
HELLO=1
NI=2
WORLD=3
I Love China.
Love all....
如果是要刪除第三行:
sed -i '3d' 1.txt
如果刪除以Love開頭的行
sed -i '/^Love/d' 1.txt
刪除包含Love的行
sed -i '/Love/d' 1.txt
參考
http://www.360doc.com/content/14/1125/19/7044580_428024359.shtml
有空就學習如下幾個命令:
https://zhidao.baidu.com/question/508817260.html?qbl=relate_question_0&word=shell%20%C8%A1%CE%C4%BC%FE%CC%D8%B6%A8%D0%D0%20%CC%ED%BC%D3