0

我的输入文件是:

zoo1
----

cat
dog
mouse

zoo2
----

lion
tiger
zebra

我希望我的输出文件是:

cat,dog,mouse
lion,tiger,zebra

知道怎么做吗?

4

4 回答 4

2

对于您问题中的示例,此单行代码有效:

 awk -v RS= '/----/{next}{gsub(/\n/,",")}7' file

或通过设置OFS and FS

awk -v RS= -v OFS="," -F'\n' '/----/{next}$1=$1' file

小测试:

kent$  awk -v RS= '/----/{next}{gsub(/\n/,",")}7' f
cat,dog,mouse
lion,tiger,zebra



kent$  awk -v RS= -v OFS="," -F'\n' '/----/{next}$1=$1' f
cat,dog,mouse
lion,tiger,zebra
于 2013-10-01T14:02:17.403 回答
2

一种方法awk

$ awk '!(NR%2){$1=$1;print}' FS='\n' OFS=',' RS= file
cat,dog,mouse
lion,tiger,zebra
于 2013-10-01T14:34:26.420 回答
0

你可以通过使用 perl 的段落模式来做到这一点:

$ perl -000 -ne 'next if /---/;print join(",",split(/\n/)),"\n"' file
cat,dog,mouse
lion,tiger,zebra

来自man perlrun

-0[octal/hexadecimal]
     specifies the input record separator ($/) as an octal or hexadecimal number.
     If there are no digits, the null character is the separator.  Other switches
     may precede or follow the digits.  For example, if you have a version of 
     find which can print filenames terminated by the null character, you can say
     this:

            find . -name '*.orig' -print0 | perl -n0e unlink

     The special value 00 will cause Perl to slurp files in paragraph mode.  
     Any value 0400 or above will cause Perl to slurp files whole, but by 
     convention the value 0777 is the one normally used for this purpose.
于 2013-10-01T14:50:19.123 回答
0

tr提供了一种非常简单易懂的方法来做到这一点。

tr -s \\n ","

http://linuxcommand.org/lc3_man_pages/tr1.html

于 2020-05-13T06:57:04.473 回答