【问题标题】:Awk removing all blank lines in a script (not with command line)awk 删除脚本中的所有空行(不使用命令行)
【发布时间】:2011-06-14 02:29:20
【问题描述】:

我正在使用 LaTeX 将 csv 文件转换为 pdf。我的 awk 脚本如下所示:

BEGIN {printf "\\documentclass[a4paper,notitlepage]{report}\n" \
"\\usepackage[utf8]{inputenc}\n"\
"\\usepackage[francais]{babel}\n"\
"\\usepackage[T1]{fontenc}\n"\
"\\usepackage{hyperref}\n"\
"\\usepackage{textcomp}\n"\
"\\usepackage[left=1cm]{geometry}\n"\
..........
{print $1"\n" \
$2"\n" \
$3"\n" \
$4"\t"\
$5"\t" \
$6"\t" \
$7"\t" \
$8"\t" \
$9"\t" \
$10"\n""\\linebreak" \
......
$39"\t"\
$40;}

END {print "\\end{document}";}

我发现了各种类型的命令来删除命令行中的空白行(awk 'NF'、awk '$0!~/^$/ {print $0}')并尝试将它们合并到脚本的末尾使用 BEGIN 和 END 语句的各种组合,但没有任何效果。

有人可以帮忙吗?非常感谢您提前...

【问题讨论】:

  • 你能问清楚一点吗?我根本没听懂一个问题。提供一些您的脚本错误处理的 csv 简单示例,并解释究竟是什么不正确,即您希望最终结果是什么。
  • @Max: csv 处理得很好,除了我在每条记录之后、\linebreak 插入之前和 \linebreak 插入之后都有空行。我需要删除那些空白行才能将 .tex 文件正确处理为 pdf。当然,如果我从命令行运行 awk NF filename,它就可以正常工作。但关键是要有一个带有单个脚本的干净文件。

标签: awk duplicates


【解决方案1】:

尝试在此行之前添加!/^$/ {print $1"\n" \

!/^$/ {print $1"\n" \

编辑:

这是另一种方法:

BEGIN {
    ...
}
!/^[[:blank:]]*$/ {    # skip blank *input* lines
    output = $1"\n" \
             $2"\n" \
             ...
             $40
    # remove blank lines from *output*
    # it also removes trailing whitespace from each line
    gsub("([[:blank:]]*\n)+", "\n", output)
    print output
}
END {
   ...
}

【讨论】:

  • 很抱歉,它不起作用。我已经按照您的说明进行了尝试,并且在 {print...} 之前也使用了花括号。
  • @Trying:您的脚本应该具有一般形式BEGIN { do-setup; print-headers} { per-line-processing } END { finalize; print-footers; do-cleanup }(不一定是所有这些东西)。因此,BEGIN 子句应该在我的回答中的行之前关闭:BEGIN { ... } !/^$/ {print ...。如果您的空白行中有空格(即它们不是真正为空的),请尝试 !/^[[:blank:]]$/ 选择器。
  • 我的开始语句是这样的: BEGIN {printf "\\documentclass[a4paper,notitlepage]{report}\n" \ (....一堆东西)"\\tableofcontents\n" ; } {FS="\t"} {print $1"\n" \ (bunch of fields....)$40;} END {print "\\end{document}";}
  • 抱歉,被 5 百万编辑卡住了:我的开始语句是这样的:BEGIN {printf "\\documentclass[a4paper,notitlepage]{report}\n" \ (....一堆东​​西)"\\tableofcontents\n"; } {FS="\t"} {print $1"\n" \ (bunch of fields....)$40;} END {print "\\end{document}";} 我试着把你的代码放在 { FS="\t"} 和之前 {print $1"\n" \.... 它仍然不起作用。我真的不知道,因为您的代码看起来确实正确。输出一切正常,\linebreak 行前后有很多空行。
  • @Trying:设置FS 应该在BEGIN 子句中完成。您的脚本应类似于BEGIN {printf "\\documentclass[a4paper,notitlepage]{report}\n" \ (.... bunch of stuff)"\\tableofcontents\n"; FS="\t"} !/^[[:blank:]]*$/ {print $1"\n" \ (bunch of fields....)$40;} END {print "\\end{document}";}。注意删除} {。抱歉,我在上一条评论中忘记了 !/^[[:blank:]]*$/ 中的星号。
猜你喜欢
  • 1970-01-01
  • 2018-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-08
相关资源
最近更新 更多