GNU awk --traditional および --posix

GNU awk --traditional および --posix

したがって、GNU awkにはmacOS awkにはないいくつかの拡張機能があります。

私のawkプログラムがmacOS awk(アクセス権なし)でも実行されていることを確認したいと思います。

GNU awkには2つの異なる互換性フラグがあり、どちらを使用するのかわかりません--traditional--posix

後者はより厳しいです。--traditionalmacOS awkとの互換性を達成するのに十分ですか?

ベストアンサー1

理由なく

  1. MacOS はgawk --traditionalRE インターバルのように POSIX の一部ですが、BWK awk (互換予定) ではない機能を実装しているため、一部の言語構成は両方のバリアントで有効ですが、両方のバリエーションで同じ意味を持ちません。
  2. MacOS awkにはGNU awkにないバグがあるため、どのオプションを提供しても、MacOSでgawkスクリプト操作が失敗する可能性があります。
  3. どちらのawkも、POSIXまたは「従来の」awk仕様によって定義されていない機能を必要に応じて実装できます。

したがって、--posixあなたが望むものに近いですが、--traditionalまだMacOSとは違いがあり、オプションや他のオプションはすべて好きなように機能しません。 gawk スクリプトが MacOS awk で同じタスクを実行することが保証されます。

  1. たとえば、gawkを使用します(レガシーモードなどのREインターバルはサポートしていませんが、{2}posixモードではサポートしています)。

    $ awk --version | head -1
    GNU Awk 5.0.1, API: 2.0
    
    $ echo 'ab{2}c' | awk --traditional '/b{2}/'
    ab{2}c
    
    $ echo 'ab{2}c' | awk --posix '/b{2}/'
    $
    
    $ echo 'ab{2}c' | awk --traditional '/b\{2\}/'
    awk: cmd. line:1: warning: regexp escape sequence `\{' is not a known regexp operator
    awk: cmd. line:1: warning: regexp escape sequence `\}' is not a known regexp operator
    ab{2}c
    

    MacOSはREインターバルをサポートしています。

    $ awk --version | head -1
    awk version 20200816
    
    $ echo 'ab{2}c' | awk '/b{2}/'
    $
    
    $ echo 'ab{2}c' | awk '/b\{2\}/'
    ab{2}c
    
  2. たとえば、gawkを使用すると、次のようになります。

    $ awk 'BEGIN{print 1 == 2 ? 3 : 4}'
    4
    
    $ awk --traditional 'BEGIN{print 1 == 2 ? 3 : 4}'
    4
    
    $ awk --posix 'BEGIN{print 1 == 2 ? 3 : 4}'
    4
    

    そしてMacOSの場合:

    $ awk 'BEGIN{print 1 == 2 ? 3 : 4}'
    awk: syntax error at source line 1
     context is
     BEGIN{print 1 >>>  == <<<
    awk: illegal statement at source line 1
    awk: illegal statement at source line 1
    

    バラよりhttps://unix.stackexchange.com/a/588743/133219これは特定のエラーに関する追加情報です。

  3. ディレクトリをファイル名として扱う別の違いは次のとおりです。

    $ mkdir foo
    $ echo 7 > bar
    

    GNU awkを使う:

    $ awk '{print FILENAME, $0}' foo bar
    awk: warning: command line argument `foo' is a directory: skipped
    bar 7
    
    $ awk --traditional '{print FILENAME, $0}' foo bar
    awk: fatal: cannot open file `foo' for reading (Is a directory)
    
    $ awk --posix '{print FILENAME, $0}' foo bar
    awk: fatal: cannot open file `foo' for reading (Is a directory)
    

    そしてMacOS awk:

    $ awk '{print FILENAME, $0}' foo bar
    bar 7
    

おすすめ記事