-1

I have list of text files, each text file contain numbers like this:

 0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5 

the numbers in the text files are comma separated.

How can I generate 6 files (using bash) starting from every parent file. Every file of these 6 new files contain group of the numbers as follow:

file0.txt contain 0 0 0 0 0 0 0 0 0 0
file1.txt contain 1 1 1 1 1 1 1 1 1 1
file2.txt contain 2 2 2 2 2 2 2 2 2 2
file3.txt contain 3 3 3 3 3 3 3 3 3 3
file4.txt contain 4 4 4 4 4 4 4 4 4 4
file5.txt contain 5 5 5 5 5 5 5 5 5 5
  • Are the output files supposed to contain a fixed number of fields, or just all the consecutive equal values? – glenn jackman Sep 22 '15 at 19:05
  • @glennjackman. Thanks! Just the consecutive series of equal numbers. – user88036 Sep 22 '15 at 19:07
0

Ruby works well for this:

ruby -e '
  ARGV.each do |filename|
    data = File.read(filename).strip.split(",")
    groups = data.group_by {|n| n}
    groups.each_pair do |n, nums|
      # you don't really say what your input filenames look like
      # I will assume they end with ".txt"
      f = filename.sub(/\.txt$/, "#{n}.txt")
      File.write(f, nums.join(" ") + "\n"}
    end
  end
' fileA.txt fileB.txt ...
  • Great!! it worked and this is what I really want. Thanks a lot genn I keep learning from you ;) – user88036 Sep 22 '15 at 19:26
1

one line answer using sed

sed 's/,/\n/g' InputFile.txt |while read line ; do     echo -n "$line ">>file$line.txt ;  done

Or multiline when in a shell:

sed 's/,/\n/g' InputFile.txt |while read line
do 
    echo -n "$line ">>file$line.txt
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy