在第一个匹配项处停止。

huangapple go评论43阅读模式
英文:

grep stop at first match

问题

You can use the -m option with grep to specify the maximum number of matches. To stop grep at the first match of ${A57}, you can use the following command:

grep -o -m 1 "${A57}.*${A29}${A14}"

This will give you the desired output:

${A57}${A37}${A18}${A44}${A15}${A28}${A29}${A29}${A29}${A29}${A14}

The -m 1 option tells grep to stop after the first match is found.

英文:

I want to grep a file that stops at the first match, example:

${A57}${A17}${A23}${A20}${A35}${A57}${A33}${A24}${A38}${A38}${A24}${A17}${A57}${A33}${A23}${A38}${A18}${E52}${A28}${A28}${A28}${A25}${A38}${A22}${A50}${A30}${A57}${A37}${A18}${A44}${A15}${A28}${A29}${A29}${A29}${A29}${A14}

When I use grep -o "${A57}.\*${A29}${A14}" I obtain this output:

${A57}${A17}${A23}${A20}${A35}${A57}${A33}${A24}${A38}${A38}${A24}${A17}${A57}${A33}${A23}${A38}${A18}${E52}${A28}${A28}${A28}${A25}${A38}${A22}${A50}${A30}${A57}${A37}${A18}${A44}${A15}${A28}${A29}${A29}${A29}${A29}${A14}

Now my question is how can I stop grep with the first match of '${A57}' so that I have this output:

${A57}${A37}${A18}${A44}${A15}${A28}${A29}${A29}${A29}${A29}${A14}

答案1

得分: 3

You can use the following translated code snippets:

使用任何 sed

$ sed -n 's/.*\(${A57}.*${A29}${A14}\).*//p' file
${A57}${A37}${A18}${A44}${A15}${A28}${A29}${A29}${A29}${A29}${A14}

或者使用支持 gensub() 的 GNU awk:

$ awk '{print gensub(/.*(${A57}.*${A29}${A14}).*/,"\",1)}' file
${A57}${A37}${A18}${A44}${A15}${A28}${A29}${A29}${A29}${A29}${A14}
英文:

You're trying to use the wrong tool. Using any sed:

$ sed -n 's/.*\(${A57}.*${A29}${A14}\).*//p' file
${A57}${A37}${A18}${A44}${A15}${A28}${A29}${A29}${A29}${A29}${A14}

or an awk that supports gensub() such as GNU awk:

$ awk '{print gensub(/.*(${A57}.*${A29}${A14}).*/,"\",1)}' file
${A57}${A37}${A18}${A44}${A15}${A28}${A29}${A29}${A29}${A29}${A14}

huangapple
  • 本文由 发表于 2023年5月11日 19:17:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76227042.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定