请解释下面提供的 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

相关内容