Terminal command equivalent of PHP implode when combining lines

后端 未结 5 1966
不知归路
不知归路 2020-12-21 07:40

I have a couple of lines and want to group the line into 5 and then implode it for MySQL IN () query.

I have made it out until this

awk          


        
相关标签:
5条回答
  • 2020-12-21 08:07

    pr is the tool for this

    $ seq 6 | pr -5ats,
    1,2,3,4,5
    6
    
    $ seq 18 | pr -5ats, 
    1,2,3,4,5
    6,7,8,9,10
    11,12,13,14,15
    16,17,18
    
    0 讨论(0)
  • 2020-12-21 08:14
    seq 16 |awk '{printf NR%5 ? (NR % 5 ==1 ? $0 : ","$0) : ","$0"\n";}'
    #output:
    1,2,3,4,5
    6,7,8,9,10
    11,12,13,14,15
    16
    
    0 讨论(0)
  • 2020-12-21 08:16

    You can do:

    awk 'NR%5==0{print s","$0; s=""; next} {if (length(s)>0){ s=s","$0 } else s=$0} END {print s}'
    

    Test it:

    $ seq 1 6 | awk 'NR%5==0{print s","$0; s=""; next} {if (length(s)>0){ s=s","$0 } else s=$0} END {print s}'
    1,2,3,4,5
    6
    $ seq 1 12 | awk 'NR%5==0{print s","$0; s=""; next} {if (length(s)>0){ s=s","$0 } else s=$0} END {print s}'
    1,2,3,4,5
    6,7,8,9,10
    11,12
    
    0 讨论(0)
  • 2020-12-21 08:22
    #!/usr/bin/awk -f
    {
      a[NR] = $0
    }
    END {
      for (b in a) {
        printf a[b] (b % 5 && b != NR ? "," : RS)
      }
    }
    

    Or one liner:

    awk '{a[NR]=$0} END {for (b in a) printf a[b] (b%5 && b!=NR ? "," : RS)}'
    
    0 讨论(0)
  • 2020-12-21 08:26

    Although not a single process awk command, you can even use paste and sed combination like this:

    $ cat file 
    1
    2
    3
    4
    5
    6
    $ paste - - - - - -d , < file | sed 's/,\+$//'
    1,2,3,4,5
    6
    $ seq 1 12 > file 
    $ cat file 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    $ paste - - - - - -d , < file | sed 's/,\+$//'
    1,2,3,4,5
    6,7,8,9,10
    11,12
    
    0 讨论(0)
提交回复
热议问题