【问题标题】:Reformat a large text file into one line strings (via BASH)将大文本文件重新格式化为一行字符串(通过 BASH)
【发布时间】:2009-10-24 10:41:28
【问题描述】:

文件1:

hello
- dictionary definitions:
hi
hello
hallo
greetings
salutations
no more hello for you
-
world
- dictionary definitions:
universe
everything
the globe
the biggest tree
planet
cess pool of organic life
-

我需要将它(对于大量单词)格式化为术语到定义格式(每个术语一行)。怎么能做到这一点?没有一个词是相同的,只有上面看到的结构是相同的。生成的文件如下所示:

hello    - dictionary definitions:    hi    hello    hallo    greetings    salutations    no more hello for you    -
world    - dictionary definitions:    universe    everything    the globe    the biggest tree    planet    cess pool of organic life    -

Awk/Sed/Grep/Cat 是通常的竞争者。

【问题讨论】:

  • 将问题更改为更具体的脚本语言/命令。

标签: linux sed awk grep cat


【解决方案1】:

谁说只有 Perl 才能优雅地做到这一点? :)

$ gawk -vRS="-\n" '{gsub(/\n/," ")}1' file
hello - dictionary definitions: hi hello hallo greetings salutations no more hello for you
world - dictionary definitions: universe everything the globe the biggest tree planet cess pool of organic life

# gawk 'BEGIN{RS="-\n";FS="\n";OFS=" "}{$1=$1}1'  file
hello - dictionary definitions: hi hello hallo greetings salutations no more hello for you
world - dictionary definitions: universe everything the globe the biggest tree planet cess pool of organic life

【讨论】:

  • 不明白。是 bar 吗?或者只是 ?
【解决方案2】:
awk 'BEGIN {FS="\n"; RS="-\n"}{for(i=1;i<=NF;i++) printf("%s   ",$i); if($1)print"-";}' dict.txt

输出:

hello   - dictionary definitions:   hi   hello   hallo   greetings   salutations   no more hello for you   -
world   - dictionary definitions:   universe   everything   the globe   the biggest tree   planet   cess pool of organic life   -

【讨论】:

  • 我爱你,伙计!这是一个该死的巨大命令——而且效果很好。
  • 请注意,如果您需要处理文件末尾的空行,则需要添加一个 if:awk 'BEGIN {FS="\n"; RS="-\n"}{if(NF&gt;2){for(i=1;i&lt;=NF;i++)printf("%s ",$i);print("-");}}' dict.txt
【解决方案3】:

perl 单行代码:

perl -pe 'chomp;s/^-$/\n/;print " "' File1

给予

 hello - dictionary definitions: hi hello hallo greetings salutations no more hello for you
 world - dictionary definitions: universe everything the globe the biggest tree planet cess pool of organic life 

这“类似于”您所需的输出。

【讨论】:

  • 不错!比上面那个更优雅。我听说 perl 的文本处理能力很棒。
  • Perl 很棒,awk 也很棒,它的祖父 :)
  • 是的,Larry Wall 肯定感谢 awk,这一点毫无疑问。
【解决方案4】:

不确定您将使用的脚本语言,这里是伪代码:

for each line
 if line is "-"
  create new line
 else
  append separator to previous line
  append line to previous line
 end if
end for loop

【讨论】:

    【解决方案5】:

    在一个单词始终为 6 行的条件下,试试这个衬里的工作原理

    sed 'N;N;N;N;N;N;N;N;s/\n/ /g' test_3
    

    【讨论】:

    • 不够灵活。你永远不知道有多少定义
    【解决方案6】:
    sed -ne'1{x;d};/^-$/{g;s/\n/ /g;p;n;x;d};H'
    awk -v'RS=\n-\n' '{gsub(/\n/," ")}1'
    

    【讨论】:

      猜你喜欢
      • 2014-10-01
      • 1970-01-01
      • 2017-11-06
      • 1970-01-01
      • 2011-07-27
      • 2023-03-19
      • 2018-07-10
      • 2017-05-23
      • 1970-01-01
      相关资源
      最近更新 更多