BREAK in AWK doesn't work

拥有回忆 提交于 2019-12-24 10:55:42

问题


I have:

AGT GTT TTA CAT TTT GTA TTT TTT TTC TAA ATT CTG AGT GTA GTC TTC CCT

My desired output is:

AGT GTT TTA CAT TTT

My code:

awk '{for (i=1;i<=NF;i++) {printf $i" "; if ($i~/TTT/) {break}}}'

However, it seems that break doesn't work cause it prints:

AGT GTT TTA CAT TTT GTA TTT TTT TTC TAA ATT CTG AGT GTA GTC TTC CCT

回答1:


As indicated on the comments, changing break for exit can make it:

awk '{for (i=1;i<=NF;i++) {printf $i" "; if ($i~/TTT/) exit}}' file

Note you can delete the brackets around an action if there is only one:

if () {command}  <== equivalent ==>   if () command

but

if () {command1; command2} <== NOT equivalent ==>  if () command1; command2



回答2:


$ cat file
AGT GTT TTA CAT TTT GTA TTT TTT TTC TAA ATT CTG AGT GTA GTC TTC CCT
$ awk '{sub(/TTT.*/,"TTT")}1' file
AGT GTT TTA CAT TTT


来源:https://stackoverflow.com/questions/19859080/break-in-awk-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!