可以漂亮地打印Awk的代码吗? [英] Is it possible to pretty print Awk's code?
问题描述
我经常发现自己写的是 Awk单行代码,随着时间的流逝,它变得越来越复杂.
Quite often I find myself writing Awk one-liners that gain complexity over time.
我知道我总是可以创建一个Awk文件来继续添加用例,但是它肯定不如在命令行上更改文本有用.
I know I can always create an Awk file where to keep adding use cases, but it is certainly not as usable as changing the text on the command line.
为此:我有什么办法可以打印Awk的代码,从而使我更有意义?
For this: is there any way I can pretty print Awk's code, so I can make more sense out of it?
例如,鉴于此:
awk 'flag{ if (/PAT2/){printf "%s", buf; flag=0; buf=""} else buf = buf $0 ORS}; /PAT1/{flag=1}' file
如何使内容更具可读性?
How can I get something a bit more readable?
推荐答案
Ed Morton告诉我 GNU awk具有-o
漂亮打印选项:
Ed Morton showed me that GNU awk has the -o
option to pretty print:
GNU Awk User's Guide, on Options
-o [文件]
-漂亮的打印[=文件]
启用awk程序的漂亮打印.表示--no-optimize
.默认情况下,在名为awkprof.out
的文件中创建输出程序(请参见配置文件).可选的 file 参数使您可以为输出指定其他文件名.如果提供了 file ,则-o
和文件之间不允许有空格.
Enable pretty-printing of awk programs. Implies --no-optimize
. By default, the output program is created in a file named awkprof.out
(see Profiling). The optional file argument allows you to specify a different file name for the output. No space is allowed between the -o
and file, if file is supplied.
注意:过去,此选项也会执行您的程序.情况不再如此.
NOTE: In the past, this option would also execute your program. This is no longer the case.
所以这里的关键是使用-o
,并使用:
So the key here is to use -o
, with:
- 不希望将输出自动存储在"awkprof.out"中.
-
-
将输出存储在stdout中. -
file
将输出存储在名为 file 的文件中.
- nothing if we want the output to be stored automatically in "awkprof.out".
-
to have the output in stdout.file
to have the output stored in a file called file.
实时观看:
$ gawk -o- 'BEGIN {print 1} END {print 2}'
BEGIN {
print 1
}
END {
print 2
}
或者:
$ gawk -o- 'flag{ if (/PAT2/){printf "%s", buf; flag=0; buf=""} else buf = buf $0 ORS}; /PAT1/{flag=1}' file
flag {
if (/PAT2/) {
printf "%s", buf
flag = 0
buf = ""
} else {
buf = buf $0 ORS
}
}
/PAT1/ {
flag = 1
}
这篇关于可以漂亮地打印Awk的代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!