在 Unix 系統裡翻資料,有時候真的像大海撈針。關鍵資訊一旦埋在幾十億位元組的日誌檔或格式各異的巨大-record 集合裡,肉眼根本抓不到。今天的「大資料」時代,這種挖掘工作更是家常便飯。
好消息是,真正需要絞盡腦汁的場合只有兩種:一種是你知道自己要找什麼,另一種是你還不知道。而該用哪套工具,取決於你落在哪一種。
grep 不只是拿來找特定字串而已。任意文字、單一單字、樣式、帶上下文的片段,它都能處理。最直白的用法是 grep this that,把 that 檔案中所有含 this 的行印出來。
$ grep find poem
finding meaning, finding comfort,
finding someone to adore
Can we find a way to be
加上 -w,就只保留「find 是獨立單字」的那些行;像 thistle、erethism 這種把 find 包在裡面的字,除非該行另有獨立的 find,否則不會出現。
$ grep -w find poem
Can we find a way to be
比方說不分大小寫地找 find,用方括號列舉首字母即可:
$ grep [Ff]ind poem
Finding answers
finding meaning, finding comfort,
finding someone to adore
Can we find a way to be
想限定「行首」用 ^,「行尾」用 $:
$ grep ^find poem
finding meaning, finding comfort,
finding someone to adore
要抓含連續兩個母音的單字,用 -E 搭配字元計次:
$ grep -E "[AEIOUaeiou]{2}" poem | head -3
All our days are filled with searching
wondering what we're looking for
finding meaning, finding comfort,
抓長度 9 到 10 個字母的字:
$ grep -E "[[:alpha:]]{9,10}" poem
All our days are filled with searching
wondering what we're looking for
All our days are filled with searching
that makes the searching more productive
抓「find 後面還接著一串非空白字元」的長字:
$ grep -E "find[^[:space:]]+" poem
finding meaning, finding comfort,
finding someone to adore
我們当然不会去 grep 詩,但同样的手法拿来挖系统文件非常顺手。下面用 -C 2 抓 processor 关键字,并附上前后各两行作为上下文;想要九行一组,把 -C 2 改成 -C 4 即可。
$ grep -C 2 processor /var/log/dmesg
Using ACPI (MADT) for SMP configuration information
Allocating PCI resources starting at 88000000 (gap:80000000:7ec00000)
Detected 3400.426 MHz processor.
Built 1 zonelists. Total pages: 524275
Kernel command line: ro root=LABEL=/1
--
CPU0: Intel(R) Xeon(TM) CPU 3.40GHz stepping 04
SMP alternatives: switching to SMP code
Booting processor 1/1 eip 11000
CPU 1 irqstacks, hard=c0779000 soft=c0759000
Initializing CPU
#1
如果你手上有一個明確的行號——例如 Perl 抱怨腳本第 73 行有問題,或者同事叫你看第 1892 行——那就用 sed 直接把那一行抓出來,省得自己數。
錯誤訊息長這樣:
"syntax error line 73 near "}else""
只印出第 73 行:
$ sed -n 73p showvars
else
光看到 else 其實沒多知道什麼。把前面幾行一起印出來,語意就清楚了:
$ sed -n 63,73p showvars
if $password eq "a_secret";
{
foreach $var (sort(keys(%ENV))){
$val = $ENV{$var};
$val =~ s|n|n|g;
$val =~ s|"|"|g;
print '${var}="${val}"n'
};
}
else
一眼就看得出來,寫 if 的人少了一個大括號,修起來不難。
sed 也能替符合條件的行加上「箭頭」,讓特定指令在整份檔案中跳出來:
$ sed '/print/{b label1; {:label1 ; s/^/# / ; s/$/ <===/ ;} }' showvars
#!/bin/bash
if $password eq "a_secret";
{
foreach $var (sort(keys(%ENV))){
$val = $ENV{$var};
$val =~ s|n|n|g;
$val =~ s|"|"|g;
#print '${var}="${val}"n'<===
};
}
else
同一個骨架稍作變化,也能直接把 print 那行程式碼註解掉,方便快速試跑。
大海撈針很難,地毯上撿針其實也不容易。但只要把幾個最常見的 Unix 指令變形一下,要找的東西就會自己浮出來——哪怕你一開始並不確定自己在找什麼。