weixin_41568110
七度&光
采纳率25%
2013-04-02 07:48

用逗号分隔(perl / sed / awk)[ duplicate ]将多行转换为一行

This question already has an answer here:

I have the following data in multiple lines:

foo
bar
qux
zuu
sdf
sdfasdf

What I want to do is to convert them with one line and comma separated:

foo,bar,qux,zuu,sdf,sdfasdf

What's the best unix one-liner to do that?

</div>

转载于:https://stackoverflow.com/questions/15758814/turning-multiple-lines-into-one-line-with-comma-separated-perl-sed-awk

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

8条回答

  • csdnceshi62 csdnceshi62 8年前

    Using paste command:

    paste -d, -s file
    
    点赞 20 评论 复制链接分享
  • csdnceshi64 游.程 8年前
    perl -pi.bak -e 'unless(eof){s/\n/,/g}' your_file
    

    This will create a backup of original file with an extension of .bak and then modifies the original file

    点赞 7 评论 复制链接分享
  • weixin_41568131 10.24 8年前
    sed -n 's/.*/&,/;H;$x;$s/,\n/,/g;$s/\n\(.*\)/\1/;$s/\(.*\),/\1/;$p'
    
    点赞 7 评论 复制链接分享
  • weixin_41568126 乱世@小熊 8年前

    Perl one-liner:

    perl -pe'chomp, s/$/,/ unless eof' file
    

    or, if you want to be more cryptic:

    perl '-peeof||chomp&&s/$/,/' file
    
    点赞 10 评论 复制链接分享
  • csdnceshi66 必承其重 | 欲带皇冠 8年前

    based on your input example, this awk line works. (without trailing comma)

    awk -vRS="" -vOFS=',' '$1=$1' file
    

    test:

    kent$  echo "foo
    bar
    qux
    zuu
    sdf
    sdfasdf"|awk -vRS="" -vOFS=',' '$1=$1' 
    foo,bar,qux,zuu,sdf,sdfasdf
    
    点赞 6 评论 复制链接分享
  • csdnceshi78 程序go 8年前

    There are many ways it can be achieved. The tool you use mostly depends on your own preference or experience.

    Using tr command:

    tr '\n' ',' < somefile
    

    Using awk:

    awk -F'\n' '{if(NR == 1) {printf $0} else {printf ","$0}}' somefile
    
    点赞 8 评论 复制链接分享
  • csdnceshi58 Didn"t forge 8年前

    xargs -a your_file | sed 's/ /,/g'

    this is more shorter way

    点赞 5 评论 复制链接分享
  • weixin_41568183 零零乙 8年前

    file

    aaa
    bbb
    ccc
    ddd
    

    xargs

    cat file | xargs
    

    result

    aaa bbb ccc ddd 
    

    xargs improoved

    cat file | xargs | sed -e 's/ /,/g'
    

    result

    aaa,bbb,ccc,ddd 
    
    点赞 7 评论 复制链接分享