2014-10-07 60 views
0

我试图以行格式将下面的输出打印到csv文件。有人可以帮助我使用awk或bash吗?以行格式打印输出的命令

Server abc.com 
osbits x64 
ostype windows 

我想打印输出这样并转发到CSV格式

abc.com x64 windows 
+0

护理接受的答案吗? – anonymous 2014-10-11 10:51:25

回答

0

与要设置输出字段分隔符(OFS),以逗号awk中,然后打印第二,第四和第六个字段与您的示例相匹配。

对于多行输入,你可以用sed加入之前的行awk的

[email protected]:~ $ cat servers.txt 
Server abc.com 
osbits x64 
ostype windows 
[email protected]:~ $ cat servers.txt | sed -e 'N;N;s/\n/ /g' 
Server abc.com osbits x64 ostype windows 
[email protected]:~ $ cat servers.txt | sed -e 'N;N;s/\n/ /g' | awk '{ OFS=","; print $2,$4,$6}' 
abc.com,x64,windows 
+0

看看编辑过的问题。输入不是一行。 – 2014-10-07 17:36:56

+0

这是当我的回应发布:) – 2014-10-07 17:47:27

0

这工作,但我敢肯定有一个更地道的方式来做到这一点:

awk '{printf "%s%s", ((NR==1)?"":", "),$2}' 
0

对于输入

Server abc.com foo.com bar.com buz.org 
osbits x64 x86 sparc ppc 
ostype windows linux solaris mac 

的awk脚本

{ 
    for (i=1;i<=NF;++i) 
     a[i][NR] = $i; 
} 
END { 
    for (i=2;i<=length(a); ++i) { 
     str = a[i][1] 
     for (j=2; j<=length(a[i]); ++j) 
      str = str "," a[i][j] 
     print str 
    } 
} 

产生

abc.com,x64,windows 
foo.com,x86,linux 
bar.com,sparc,solaris 
buz.org,ppc,mac 
0

假设输入文件,file.txt,看起来是这样的:

Server abc.com 
osbits x64 
ostype windows 

以下所有的解决方案会产生这样的输出:

Server,abc.comosbits,x64ostype,windows 
  1. AWK

    awk '{printf "%s,%s",$1,$2}END{print ""}' file.txt 
    
  2. 的Perl

    perl -000ane 'print join ",",@F,"\n"' file.txt 
    
  3. while read a b ; do printf "%s,%s" "$a" "$b"; done < file.txt; echo