以下に提供されているawkスクリプトを説明してください。

以下に提供されているawkスクリプトを説明してください。

誰もが以下に書かれたAWKスクリプトを段階的に説明してもらえますか?

フラットファイルデータをフォーマットするために、スクリプトに次のコードを書きました。再利用できるように知りたかったです。私はUNIXユーザーではありませんが、タスクは私に割り当てられました。助けてください!

awk -vsep=$SEPARATOR 'NR>2{if(NF){if(!s){gsub(" *"sep"[ \t]*",sep);printf "%d%s\n",NR-2,$0}}else s=1}' file_name > new_file

 # where $SEPARATOR = ';'

よろしくお願いします。

ベストアンサー1

コマンドラインオプションは、ユーザーが指定した-vsep=$SEPERATORようにawk変数sep(検索/置換に使用されます)を設定します。;あなたの場合。

# NR = Number of current Record, or line number
# Skip the first line
if ( NR > 2 ) {

  # NF = Number of fields in the current record
  # If the line contains something other than a blank line or the 
  # awk field separator characters (whitespace by default)
  if ( NF ) {

    # If we have not seen a blank line (script flag s)
    if ( !s ) {

      # Search the current line repeatedly (gsub) for any number of spaces (" *") 
      # before a ";" then any number of spaces or tabs ([ \t]*) after the `;`
      # and replace it all with just a ";"
      gsub( " *"sep"[ \t]*", sep );

      # Print the line number, 0 based (NR-2) as a signed decimal integer (`%d`)
      # then the complete line ($0) followed by a new line character (\n)
      printf "%d%s\n", NR-2, $0;
    }

  } else { 

    # Set the "seen a blank line" flag
    s = 1
  }

}

file_name > new_file名前付きの新しいファイルに出力を書き込みます。new_file

ちなみに、スクリプトを次のように構成すると、空行の後ろにデータが多いと、はるかに読みやすく高速化されます。

awk -vsep=$SEPERATOR '{

# Skip the first line
if (NR == 1) { next; }

# Stop processing if we see a blank line
if (NF == 0) { exit; }

# Remove spaces before and spaces/tabs after separator
gsub( " *"sep"[ \t]*", sep );

# Print the line with a record number starting from 0
printf "%d%s\n", NR-2, $0;

}' file_name > new_file

おすすめ記事