Bash Shell中常用命令之cut,grep(一)
阿新 • • 發佈:2019-01-01
科研日常中會在Linux系統下使用到很多shell 命令,有很多十分有用的命令。當要實現一個功能時,可能需要非常簡單的幾個單詞和字母即可,在此將自己常用的命令做一總結,方便查閱。
1. 選取命令cut
cut主要用來對同一行裡的資料進行分解,對字串切割。
cut -d '分割字元' -f fields #用於分割字元;
cut -c 字元範圍 #用於分割排列整齊的資訊;
舉例:
$ a=123:456:789 $ echo $a | cut -d ':' -f 2 456 $ b=`echo $a | cut -d ':' -f 2` ; echo $b 456 $ c=` echo $a | cut -b 5-7` ; echo $c 456 $ echo $a | cut -c 5-7 456
2. 查詢命令grep
grep主要用來查詢,若有需要的資訊,則會查找出來;
grep [-acinv] [--color=auto] '查詢字串' filename
-a: 將binary檔案以text檔案的方式進行查詢資料;
-c: 計算找到‘查詢字串‘的次數;
-i: 忽略大小寫;
-n: 輸出行號;
-v: 反向選擇,即顯示出沒有查詢字串的行;
--color=auto: 將找到的關鍵字用顏色顯示;
舉例:
檔案data.txt內容如下:
001 liming 1995 aaa
002 lily 1988 aaa
003 danilise 1999 bbb
004 david 2003 bbb
$ grep 'aaa' data.txt #輸出查詢到的內容;
001 liming 1995 aaa
002 lily 1988 aaa
$ grep -c 'aaa' data.txt #輸出查詢到的個數;
2
$ grep -n 'aaa' data.txt #加上行號;
1:001 liming 1995 aaa
2:002 lily 1988 aaa
$ cat data.txt | grep 'bbb'
003 danilise 1999 bbb
004 david 2003 bbb
cut與grep聯合使用
舉例:
$ cat data.txt | grep 'bbb' | cut -d ' ' -f2 danilise david