Is there a way to avoid “newline in string” errors in awk?

China☆狼群 提交于 2021-02-05 06:21:50

问题


How are cmdline args containing newline chars passed to awk? See two examples below:

awk -v s='text' 'BEGIN { print(s) }'

text

awk -v s=$'\n''text' 'BEGIN { print(s) }'

awk: newline in string 
text... at source line 1

回答1:


What you have would work as-is with gawk. With OSX (BSD) awk like you're using, either don't put a linefeed character in the string.

$ awk -v s='\ntext' 'BEGIN{ print s }'

text

or escape it:

awk -v s='\
text' 'BEGIN{ print s }'

text

or (portably with any awk) don't pass it using -v but as an argument instead:

$ awk 'BEGIN{s=ARGV[1]; ARGV[1]=""; print s }' $'\n''text'

text


来源:https://stackoverflow.com/questions/50555780/is-there-a-way-to-avoid-newline-in-string-errors-in-awk

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