Home > Back-end >  To split and arrange number in single inverted
To split and arrange number in single inverted

Time:01-08

I have around 65000 products codes in a text file.I wanted to split those number in group of 999 each .Then-after want each 999 number with single inverted commas separated by comma.

Could you please suggest how I can achieve above scenario through Unix script.

87453454
65778445
.
.
.
.

Till 65000 productscodes

Need to arrange in below pattern:

'87453454','65778445',

CodePudding user response:

With Perl and array slicing:

perl -0777 -nE '
    my @arr = split /\n/;
    for (my $i=0; $i<=$#arr; $i =999) {
        say map { defined $_ and join ",", qq/\047$_\047/ } @arr[$i..($i 998)]
    }
' file

The loop does this

CodePudding user response:

With awk:

awk '
      c == 1 { out = "\047" $0 "\047"; next }
             { out = out ",\047" $0 "\047" }
    c == 999 { print out; c = 0 }
    END { if (c) print out }
' file


Or, with GNU sed:

sed "
:a
0~999{
:b
    s/\n/','/g
    s/^/'/
    s/$/'/
    p
    d
}
\$bb
N
ba" file

CodePudding user response:

If your input file only contains short codes as shown in your example, you could use the following hack:

xargs -L 999 bash -c "printf \'%s\', \"\$@\"; echo" . <inputFile >outputFile

Alternatively, you can use this sed command:

sed -En -e"s/(.*)/'\1',/; H" -e{'0~999','$'}'{z;x;s/\n//g;p}' <inputFile >outputFile
  • s/(.*)/'\1',/ wraps each line in '...',
  • but does not print it (-n)
  • instead H stores the modified line in the so called hold space; a single string variable, where the current line is appended after a line break.
  • Every 999 lines (0~999) and at the end of the input file ($) ...
  • ... that hold space is then printed and cleared (z;x;...;p) while deleting the linebreaks (s/\n//g)
  • Related