簡體   English   中英

Grep在每行中首次出現

[英]Grep first occurence in each line

我有一個帶有ID列表的文件,如下所示

OG1: apple|fruits_1 cucumber|veg_1 apple|fruits_1  carrot|veg_2
OG2: apple|fruits_5 cucumber|veg_1 apple|fruits_1  pineapple|fruit_2
OG3: cucumber|veg_1 apple|fruits_9  carrot|veg_2
OG4: apple|fruits_3 cucumber|veg_1 apple|fruits_4  pineapple|fruit_7
OG5: pineapple|fruit_2 pineapple|fruit_2 apple|fruits_1 pineapple|fruit_2
OG6: apple|fruits_5 apple|fruits_1 apple|fruits_6  apple|fruits_7

現在,我要提取首次出現的apple | 在每一行中給我

 OG1: apple|fruits_1
 OG2: apple|fruits_5
 OG3: apple|fruits_9
 OG4: apple|fruits_3
 OG5: apple|fruits_1
 OG6: apple|fruits_5

我試過了

  grep -w -m 1 "apple" sample.txt

這只會給我

  OG1: apple|fruits_1 cucumber|veg_1 apple|fruits_1  carrot|veg_2

如果awk適合您:

將輸入行保存到sample.csv文件中。

 awk '{for(x=1;x<=NF;x++){if(substr($x,0,6)=="apple|"){print $1, $x; next}}}' sample.csv
  • 使用for循環迭代每行的字段
  • 檢查子字符串substr($x, 0, 6)等於“ apple |” 或不。 如果是通過print $1, $x來打印字段print $1, $x然后使用next忽略當前行的其余字段

輸出:

OG1: apple|fruits_1
OG2: apple|fruits_5
OG3: apple|fruits_9
OG4: apple|fruits_3
OG5: apple|fruits_1
OG6: apple|fruits_5

sed版

sed 's/\([[:blank:]]apple|[^[:blank:]]*\).*/\1/;s/:.*[[:blank:]]apple/: apple/;/apple/!d' YourFile

# assuming blank are space
sed 's/\( apple|[^ ]*\).*/\1/;s/:.* apple/: apple/;/apple/!d' YourFile

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM