如何在awk中实现类似Python格式化字符串的可读性打印?
Awk里有没有类似Python F-String的写法?
先贴一下你提到的几种写法:
你目前用的Awk printf写法
awk -v one="one" -v two="two" -v three="three" '{ printf "hello %s, sup %s? Bye %s", one, two, three }'
你尝试过的拼接写法
awk -v one="one" -v two="two" -v three="three" '{ print "hello", one, "sup", two, "? Bye", three, "." }'
参考的Python F-String写法
one = "one" two = "two" three = "three" print(f'hello {one}, sup {two}? Bye {three}.')
遗憾的是,Awk本身没有原生支持这种直接在字符串里嵌入变量的语法,不过可以用一些小技巧模拟类似效果:
方法1:自定义函数实现变量替换
如果用的是GNU Awk(gawk),可以写个简单函数把字符串里的{变量名}替换成实际值:
awk -v one="one" -v two="two" -v three="three" ' function f_str(s) { while (match(s, /{[a-zA-Z0-9_]+}/)) { var_name = substr(s, RSTART+1, RLENGTH-2) s = gensub(/{[a-zA-Z0-9_]+}/, (var_name in this)?this[var_name]:"", 1, s) } return s } BEGIN { this["one"] = one; this["two"] = two; this["three"] = three print f_str("hello {one}, sup {two}? Bye {three}.") }'
这个思路是维护一个变量映射表,循环替换字符串里的占位符,适合需要多次复用这种格式的场景。
方法2:简化版sprintf写法
如果只是追求写法紧凑,sprintf可以直接嵌在print里,比拼接写法整洁很多:
awk -v one="one" -v two="two" -v three="three" 'BEGIN { print sprintf("hello %s, sup %s? Bye %s.", one, two, three) }'
日常写脚本的话,最推荐的还是原生的printf/sprintf——虽然不如F-String直观,但效率最高,也是Awk的标准用法,不需要额外的函数逻辑。
内容的提问来源于stack exchange,提问作者Saeed
相关产品推荐
相关产品推荐

