2012-10-23 19 views
0

我試圖從該行的第一部分獲取行的第二部分包含模式的行。無法使用awk匹配字符串中的正則表達式

$ cat file.txt 
String1 is a big string|big 
$ awk -F'|' ' { if ($2 ~ /$1/) { print $0 } } ' file.txt 

但它不工作。

我無法找出這裏有什麼錯誤。

有人可以幫忙嗎?

+0

看來你的意思是「該行的第一部分包含該行的第二部分」,不是嗎? – doubleDown

回答

2

兩件事:沒有斜槓,你的數字是倒退。

awk -F\| '$1~$2' file.txt 
0

我想你的意思是第一部分字符串的一部分應該是第二部分的一部分。如果這是你想要的!然後,

awk -F'|' '{n=split($1,a,' ');for(i=1,i<=n;i++){if($2~/a[i]/)print $0}}' your_file 
0

有令人驚訝的很多事情錯了你的命令行:

1) You aren't using the awk condition/action syntax but instead needlessly embedding a condition within an action, 
2) You aren't using the default awk action but instead needlessly hand-coding a print $0. 
3) You have your RE operands reversed. 
4) You are using RE comparison but it looks like you really want to match strings. 

您可以通過修改您的命令來解決上述的第一個3:

awk -F'|' '$1~$2' file.txt 

但我認爲你真正想要的是「4」,這意味着你需要這樣做:

awk -F'|' 'index($1,$2)' file.txt