Ordering and creating an Unix file
I have an data file in Unix which contains the following records:
1
2
3
4
5
6
I will pass a parameter based on which a new file should be created. For example, it the parameter value is 2, the new file will be:
1 2
3 4
5 6
Similarly, if the parm is 3, then:
1 2 3
4 5 6
Can s开发者_Python百科omeone give me some hints on how to do this?
Thanks, Visakh
You can use this perl one-liner:
perl -e "map chomp, @a=<>; print join(' ', splice @a,0,2).$/ while @a;" <(seq 6)
# 1 2
# 3 4
# 5 6
perl -e "map chomp, @a=<>; print join(' ', splice @a,0,3).$/ while @a;" <(seq 6)
# 1 2 3
# 4 5 6
This you can easily incorporate into a shell script:
n=3
perl -e "map chomp, @a=<>; print join(' ', splice @a,0,$n).$/ while @a;" <file>
#!/usr/bin/perl -w
# formatter.pl
use strict;
use warnings;
my $newlineCnt = $ARGV[1];
if (! defined $newlineCnt) { $newlineCnt = 1; }
my $idx = 0;
while (<>) {
if ($idx == $newlineCnt) { print "\n"; $idx = 0; }
$idx++;
print "$_ ";
}
On the command line, leaving out the parameter defaults to 1
:
$ formatter.pl < testData.txt
1
2
3
4
5
6
On the command line, specifying 2
as the test parameter:
$ formatter.pl 2 < testData.txt
1 2
3 4
5 6
精彩评论