gpt4 book ai didi

awk - 是否可以漂亮地打印 Awk 的代码?

转载 作者:行者123 更新时间:2023-12-04 12:16:04 24 4
gpt4 key购买 nike

我经常发现自己在写作 Awk one-liners随着时间的推移变得复杂。

我知道我总是可以创建一个 awk 文件来继续添加用例,但它肯定不如更改命令行上的文本有用。

为此:有什么方法可以漂亮地打印 Awk 的代码,以便我可以更有意义地使用它?

例如,鉴于此:

awk 'flag{ if (/PAT2/){printf "%s", buf; flag=0; buf=""} else buf = buf $0 ORS}; /PAT1/{flag=1}' file

我怎样才能得到一些更具可读性的东西?

最佳答案

Ed Morton showed me GNU awk 有 -o pretty-print 的选项:

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 , 和:
  • 如果我们希望输出自动存储​​在“awkprof.out”中,则什么都没有。
  • -在标准输出中有输出。
  • file将输出存储在名为 file.txt 的文件中。

  • 现场观看:
    $ 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 - 是否可以漂亮地打印 Awk 的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55745956/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com