保留字段之间的间距:
$ cat file
a b c d e f
$ gawk -v col=3 '{print gensub("([[:space:]]*([^[:space:]]+[[:space:]]+){" col-1 "})[^[:space:]]+","\\1FUNCTION($col)","")}' file
a b FUNCTION($col) d e f
或者如果您实际上正在寻找要传递给 FUNCTION() 的列值:
$ gawk -v col=3 '{print gensub("([[:space:]]*([^[:space:]]+[[:space:]]+){" col-1 "})([^[:space:]]+)","\\1FUNCTION(\\3)","")}' file
a b FUNCTION(c) d e f
$ gawk -v col=4 '{print gensub("([[:space:]]*([^[:space:]]+[[:space:]]+){" col-1 "})([^[:space:]]+)","\\1FUNCTION(\\3)","")}' file
a b c FUNCTION(d) e f
或者:
$ gawk -v col=3 '{print gensub("([[:space:]]*([^[:space:]]+[[:space:]]+){" col-1 "})[^[:space:]]+","\\1FUNCTION($"col")","")}' file
a b FUNCTION($3) d e f
$ gawk -v col=4 '{print gensub("([[:space:]]*([^[:space:]]+[[:space:]]+){" col-1 "})[^[:space:]]+","\\1FUNCTION($"col")","")}' file
a b c FUNCTION($4) e f
上面使用 GNU awk 进行 gensub(),您可以在其他 awk 中使用多个 sub() 或 match()+substr() 完成相同的操作。
从其他人的答案看来,您实际上可能想在字段的值上调用 FUNCTION(),而不是打印 FUNCTION(field)。如果是这种情况,那么您只需执行以下操作:
$ gawk -v col=4 '{print gensub("([[:space:]]*([^[:space:]]+[[:space:]]+){" col-1 "})[^[:space:]]+","\\1"FUNCTION($col),"")}' file
例如,如果 FUNCTION 是 toupper():
$ gawk -v col=4 '{print gensub("([[:space:]]*([^[:space:]]+[[:space:]]+){" col-1 "})[^[:space:]]+","\\1"toupper($col),"")}' file
a b c D e f