簡體   English   中英

獲取每行的grep匹配的最后一列

[英]Getting the last column of a grep match for each line

假設我有

this is a test string
this is a shest string
this est is another example of sest string

我想在單詞[tsh] EST中最后一個“ t ”字符串中的字符編號,如何獲取? (在bash中)EDIT2:如果我沒有記錯的話,我可以用[tsh] * est得到想要的子字符串。

我不能依靠第一個匹配項(awk where = match(regex,$ 0)),因為它給出了第一個字符的位置,但是匹配項的大小並不總是相同的。

編輯:預期的輸出->

last t of [tsh]*est at char number: 14
last t of [tsh]*est at char number: 15
last t of [tsh]*est at char number: 35

希望我很清楚,我想我對這個問題編輯了太多次了!

你怎么了

where=match(regex,$0) 

match的語法錯誤。 其字符串后跟正則表達式。 那就是match($0, regex)

更正

$ awk '{print match($0, "t[^t]*$")}' input
17
18
38

編輯

在單詞[tsh] EST中獲取最后一個“ t”字符串中的字符編號,

$ awk '{match($0, "(t|sh|s)est"); print RSTART+RLENGTH-1}' input
14
15
35

要么

一個簡單得多的版本

$ awk 'start=match($0, "(t|sh|s)est")-1{$0=start+RLENGTH}1' input
    14
    15
    35

感謝吉德的建議

編輯

要使用OP提供的正則表達式

$ awk '{for(i=NF; match($i, "(t|sh|s)*est") == 0 && i > 0; i--); print index($0,$i)+RLENGTH-1;}' input
14
15
35

您可以使用OP提供的正則表達式來使用該awk:

awk -v re='[tsh]*est' '{
    i=0;
    s=$0;
    while (p=match(s, re)) {
       p+=RLENGTH;
       i+=p-1;
       s=substr(s, p)
    }
    print i;
}' file
14
15
35

嘗試:

awk '{for (i=NF;i>=0;i--) { if(index ($i, "t") != 0) {print i; break}}}' myfile.txt

這將打印最后一個包含t單詞的列

awk '{s=0;for (i=1;i<=NF;i++) if ($i~/t/) s=i;print s}' file
5
5
8

awk '{s=w=0;for (i=1;i<=NF;i++) if ($i~/t/) {s=i;w=$i};print "last t found in word="w,"column="s}'
last t found in word=string column=5
last t found in word=string column=5
last t found in word=string column=8

暫無
暫無

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

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