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
-

我需要将此格式(对于大量单词列表)格式化为术语到定义格式(每个术语一行)。怎么能实现这个目标?没有一个词是相同的,只有上面看到的结构。结果文件看起来像这样:

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是常见的竞争者。

有帮助吗?

解决方案

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   -

其他提示

谁说只有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

OR

# 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

perl one-liner:

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 

这就像'你需要的输出'。

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

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

尝试这个衬垫适用于一个单词

总是6行的条件
sed 'N;N;N;N;N;N;N;N;s/\n/ /g' test_3
sed -ne'1{x;d};/^-$/{g;s/\n/ /g;p;n;x;d};H'
awk -v'RS=\n-\n' '{gsub(/\n/," ")}1'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top