Reputation: 2929
I have the following 4 x 3 matrix with fields separated by a space.
Input
12.34 34.3 2.34
1.23 45.78 79.56
1.45 78.5 23.50
78.45 23.33 45.8
How to duplicate this matrix n times, in this case 2 times using awk
or sed
?
Desired output
12.34 34.3 2.34
1.23 45.78 79.56
1.45 78.5 23.50
78.45 23.33 45.8
12.34 34.3 2.34
1.23 45.78 79.56
1.45 78.5 23.50
78.45 23.33 45.8
Thanks for your help.
Tony
Upvotes: 1
Views: 203
Reputation: 58430
This might work for you:
sed ':a;N;$!ba;:b;p;x;s/^/x/;/x\{2\}/d;x;bb' matrix.txt
Where /x\{2\}/
acts as a counter i.e. repeat 12 times change to /x\{12\}/
Upvotes: 1
Reputation: 161694
$ for i in {1..2}; do cat matrix.txt; done
$ sed -n 'H; ${g;s/.*/&&/p}' matrix.txt
To duplicate this matrix 10
times, just change 2
(&&
) to 10
(&&&&&&&&&&
)
Upvotes: 1
Reputation: 753990
The easiest way if the matrix is in a file matrix.txt
is with cat
:
cat matrix.txt matrix.txt
You can achieve essentially the same effect with sed
:
sed 's/^//' matrix.txt matrix.txt
There aren't many other ways to do it easily with sed
. You can also pull the same stunt with awk
:
awk '{print $0}' matrix.txt matrix.txt
There's also a devious shorthand:
awk 1 matrix.txt matrix.txt
(Hint: the default action is print $0
.)
Using awk
, you can also arrange to read the file just once:
awk '{line[NR] = $0}
END { for (j = 1; j <= 2; j++) { for (i = 1; i <= NR; i++) print line[i] } }' \
matrix.txt
This is a space-time trade-off; awk
is internalizing a copy of the file and regurgitating it twice;
Upvotes: 1
Reputation: 455122
To repeat it N times you can use:
perl -ne '{$x.=$_}END{print $x x N}' file
In your case replace N
with 2
.
Upvotes: 1
Reputation: 45662
I think you need to provide some more context; in what form is the original matrix and what would you like to do with it? Other than that, use:
$ cat matrix
12.34 34.3 2.34
1.23 45.78 79.56
1.45 78.5 23.50
78.45 23.33 45.8
$ cat matrix matrix
12.34 34.3 2.34
1.23 45.78 79.56
1.45 78.5 23.50
78.45 23.33 45.8
12.34 34.3 2.34
1.23 45.78 79.56
1.45 78.5 23.50
78.45 23.33 45.8
Upvotes: 3
Reputation: 140367
awk '1' ./infile ./infile
sed -n 'p' ./infile ./infile
cat ./infile ./infile
Upvotes: 4