![從同一字串中提取行](https://rvso.com/image/36017/%E5%BE%9E%E5%90%8C%E4%B8%80%E5%AD%97%E4%B8%B2%E4%B8%AD%E6%8F%90%E5%8F%96%E8%A1%8C.png)
我有一個這樣的表:
以及一個包含第三列中的 2 個字串的檔案:applepotato
我想提取標題和包含字串 apple 和potato 的所有行以獲得此
謝謝
答案1
使用awk
:
awk 'FNR == 1 || /potato|apple/'
使用sed
:
sed -n '1p; /potato\|apple/p'
potato|apple
在這兩種情況下,都會列印行號 1 和任何相符的行。
答案2
這是純文字的 txt 表:
A B C D E
21 63 apple yellow 5
23 69 lemon green 6
45 135 orange yellow 7
67 201 mango green 4
54 162 potato maroon 5
雖然我可以想到一個複雜度較低的解決方案,但我認為這有點黑客:-)假設表 txt 檔案被稱為table1
$ head -1 table1 && grep '\b\(potato\|apple\)\b' table1
這將獲取第一行並將grep
結果附加到其中。\b
是一個詞邊界。因此,這將確保像「grapple(hook)」這樣的字被過濾掉:)另一個更複雜的解決方案將假設 A、B、C... 由製表符分隔\t
:
$ grep '\(\b\(potato\|apple\)\b\|\([A-Z]\|\(\t\|\n?$\)\)\)' table1