我有文本文件列表,每个文本文件都包含如下数字:
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
文本文件中的数字以逗号分隔。
如何从每个父文件开始生成 6 个文件(使用 bash)。这 6 个新文件中的每个文件都包含一组数字,如下所示:
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
答案1
使用 sed 一行回答
sed 's/,/\n/g' InputFile.txt |while read line ; do echo -n "$line ">>file$line.txt ; done
或者在 shell 中时多行:
sed 's/,/\n/g' InputFile.txt |while read line
do
echo -n "$line ">>file$line.txt
done
答案2
Ruby 在这方面效果很好:
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 ...