2016-04-25 44 views
0

我想egrep包含特定字符的行。 當我執行單egrep的,它工作正常egrep動態輸出

egrep -w -h -R 'name' /path/file1.txt > /path/file2.txt 

但是,當我使用循環執行多次的egrep,輸出都是空的。

for i in {Adam Bob Chuck Dan Eli Frank}; do egrep -w -h -R 'i' /path/file1.txt > /path/name"$i".txt; done 

我再次檢查了單個egrep的輸出文件,每個輸出文件都應該有一些信息。我在這裏做錯了,但我不知道它是什麼..

感謝您的幫助!

+0

你在用什麼外殼? Bash不應該在列表中需要大括號,並且您需要使用'「$ i」'而不是''i''。 – jkiiski

+0

我正在使用Bash。我只是試着用「$ i」代替'i',並且它工作!謝謝!!! –

回答

2

由於您調用grep併爲每個名稱解析整個輸入文件一次,因此效率極低(請參閱https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice)。

只需讀取輸入文件一次:

awk -v names='Adam Bob Chuck Dan Eli Frank' ' 
    BEGIN { split(names,list) } 
    { 
     for (i in list) { 
      if ($0 ~ ("\\<" list[i] "\\>")) { 
       print > ("/path/name" i ".txt") 
      } 
     } 
    } 
' /path/file1.txt 

以上使用GNU AWK word邊界(\<\>),與其他awks你只需要改變正則表達式比較:$0 ~ ("(^|[^[:alnum:]_])" list[i] "([^[:alnum:]_]|$)")