Specify other flags in awk script header

喜欢而已 提交于 2020-06-06 08:26:11

问题


I want to write an awk script file using the #!/bin/awk -f header, but I want this script to always use : as a field separator. But for some reason writing #!/bin.awk -F: -f gives me a syntax error. I also want this script to always run on the same file, so I'd like to hardcode that as well. Basically, what I want to work is this:

#!/bin/awk -F: -f -- /etc/passwd

followed by some awk code


回答1:


Something like this should do:

#!/bin/awk -f              # using the #!/bin/awk -f
BEGIN {
    FS=":"                 # always use : as a field separator
    ARGC=2
    ARGV[1]="/etc/passwd"  # always run on the same file
}
$3==0 {                    # followed by some awk code
    print $1
}

Run it:

$ chmod u+x program.awk
$ ./program.awk
root



回答2:


Never use a shebang to call awk as that has no worthwhile benefit over simply calling awk within your shell script but robs you of the ability to separate arguments passed to your shell script into values for the shell to process, values for awk to process use -v, values for awk to process using assignments at the end of the script and file names for awk to run on.

Just write:

#!/bin/env bash
awk -F':' '
whatever
' /etc/passwd

so that if you had to you could trivially tweak it to:

#!/bin/env bash
sort "$1" |
awk -F':' -v foo="$2" '
whatever
' - FS="$3" "$4"

or whatever else you need to do to use the arguments passed to your shell script most appropriately.



来源:https://stackoverflow.com/questions/61000804/specify-other-flags-in-awk-script-header

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