如何使用awk提取引用字段?

mmo*_*nem 6 linux bash scripting awk

我在用

awk '{ printf "%s", $3 }'
Run Code Online (Sandbox Code Playgroud)

从空格分隔的行中提取一些字段.当我引用字段时,我得到部分结果.请问有谁提出解决方案吗?

gho*_*g74 6

下次显示您的输入文件和所需的输出.要获得引用的字段,

$ cat file
field1 field2 "field 3" field4 "field5"

$ awk -F'"' '{for(i=2;i<=NF;i+=2) print $i}' file
field 3
field5
Run Code Online (Sandbox Code Playgroud)

  • @mmonem那么这可能有用:http://serverfault.com/questions/11028/do-you-have-any-useful-awk-and-grep-scripts-for-parsing-apache-logs (2认同)

sch*_*hot 1

这其实是相当困难的。我想出了以下awk脚本,该脚本手动分割行并将所有字段存储在数组中。

{
    s = $0
    i = 0
    split("", a)
    while ((m = match(s, /"[^"]*"/)) > 0) {
        # Add all unquoted fields before this field
        n = split(substr(s, 1, m - 1), t)
        for (j = 1; j <= n; j++)
            a[++i] = t[j]
        # Add this quoted field
        a[++i] = substr(s, RSTART + 1, RLENGTH - 2)
        s = substr(s, RSTART + RLENGTH)
        if (i >= 3) # We can stop once we have field 3
            break
    }
    # Process the remaining unquoted fields after the last quoted field
    n = split(s, t)
    for (j = 1; j <= n; j++)
        a[++i] = t[j]
    print a[3]
}
Run Code Online (Sandbox Code Playgroud)