三劍客過濾長字符串
記一次過濾文件內容,三劍客awk、grep、sed過濾指定字段、列後,怎料其中混雜編碼字符串,這不是我們想要的。所幸,找到了規律,那就是 它 很長…,直接幹掉長字符串即可! 下邊是三把劍具體實現!
我有三把劍,一把awk,一把grep,一把sed
[root@centos]# cat test
hello
helloword
test66
awk式
- 且看,統計字符串長度,用到招式 length() 函數
[root@centos]# echo "hello" | awk '{print length($1)}'
5
如看官所願,得到字符串的長度 5
- 連招,加 if 語句,輸出指定的字符串長度內容小於等於6的
[root@centos]# awk '{ if ( length($0) <=6 ) print $0}' test
hello
test66
grep式
[root@centos]# egrep -w '^.{1,6}' test
hello
test66
- egrep參數:相當於 grep -E ,用於匹配正則
- -w參數:僅跟模式匹配的字符串
- ^. 參數:表示以任意字符開頭
sed式
[root@centos]# sed -n '/^.\{7,\}/!p' test
hello
test66
- -n參數:–silent,配合編輯命令只打印符合條件字符串
- !p參數:符合條件的不打印,p即爲打印輸出
- \參數:轉義字符,轉義 { }
各位看官,江湖再會!