是否可以漂亮地打印 Awk 的代码?
Is it possible to pretty print Awk's code?
我经常发现自己写的 随着时间的推移变得越来越复杂。
我知道我总是可以创建一个 Awk 文件来继续添加用例,但它肯定不如在命令行上更改文本有用。
对此:有没有什么方法可以很好地打印 Awk 的代码,以便我可以从中理解更多?
例如,鉴于此:
awk 'flag{ if (/PAT2/){printf "%s", buf; flag=0; buf=""} else buf = buf [=10=] ORS}; /PAT1/{flag=1}' file
我怎样才能让内容更具可读性?
GNU awk 有 -o
选项来漂亮打印:
GNU Awk User's Guide, on Options
-o[file]
--pretty-print[=file]
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
,with:
- nothing 如果我们希望输出自动存储在 "awkprof.out".
-
在标准输出中输出。
file
将输出存储在名为 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 [=11=] ORS}; /PAT1/{flag=1}' file
flag {
if (/PAT2/) {
printf "%s", buf
flag = 0
buf = ""
} else {
buf = buf [=11=] ORS
}
}
/PAT1/ {
flag = 1
}
我经常发现自己写的
我知道我总是可以创建一个 Awk 文件来继续添加用例,但它肯定不如在命令行上更改文本有用。
对此:有没有什么方法可以很好地打印 Awk 的代码,以便我可以从中理解更多?
例如,鉴于此:
awk 'flag{ if (/PAT2/){printf "%s", buf; flag=0; buf=""} else buf = buf [=10=] ORS}; /PAT1/{flag=1}' file
我怎样才能让内容更具可读性?
-o
选项来漂亮打印:
GNU Awk User's Guide, on Options
-o[file]
--pretty-print[=file]Enable pretty-printing of awk programs. Implies
--no-optimize
. By default, the output program is created in a file namedawkprof.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
,with:
- nothing 如果我们希望输出自动存储在 "awkprof.out".
-
在标准输出中输出。file
将输出存储在名为 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 [=11=] ORS}; /PAT1/{flag=1}' file
flag {
if (/PAT2/) {
printf "%s", buf
flag = 0
buf = ""
} else {
buf = buf [=11=] ORS
}
}
/PAT1/ {
flag = 1
}