![](/img/trans.png)
[英]CSV - Grep a particular pattern, print first match and the first line of that file
[英]Limit grep to first match per line
我正在嘗試 grep 用於在該行的第一個句點之前具有字母a
的所有行。
這是一個示例文件:
test123a.hello
example.more-test-a.xyz
stacka.tester.this
nothing.nothing.nothing
在上面的示例中,我想要grep
這兩條線:
test123a.hello
stacka.tester.this
這是我嘗試過的:
grep ".*a\." test.txt
這得到了我想要的兩條線,但它也得到了這條線,我不想要,因為a
在第二個時期之前,而不是第一個時期:
example.more-test-a.xyz
我如何將其限制為僅在第一期之前獲得帶有a
的行?
$ grep '^[^.]*a\.' test.txt
test123a.hello
stacka.tester.this
^
在行首限制匹配[^.]*
匹配除.
之外的任何字符字符,零次或多次a
字符a
\.
從字面上匹配字符.
你也可以在這里使用awk
,它更適合基於字段的處理
$ # 'a' as last character for first field
$ awk -F'.' '$1 ~ /a$/' test.txt
test123a.hello
stacka.tester.this
$ # 'a' as last character for second field
$ awk -F'.' '$2 ~ /a$/' test.txt
example.more-test-a.xyz
如果你覺得output很多,你可以試試
grep ".*a." 測試.txt | 較少的
你可以試試[編輯]
grep ".*a." test.txt | grep -v "\([^a]\.\)\{1,\}.*a."
這將執行您的第一個 grep 並拒絕任何帶有“a”的內容。 前面有一個點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.