Line duplication with awk?!

So while this seemed totally trivial it turned out to be much more difficult than I had thought.

I have a file with 3 rows, and I "just" want to add each field n number of times. E.g.

> cat file.txt
0.5
-0.1
0.6

for n=3 into:

cat newfile.txt
0.5 0.5 0.5
-0.1 -0.1 -0.1
0.6 0.6 0.6

I thought this would be straightforward with awk.
If I didn't need it to be flexible, this works fine:

awk '{print $0 $0 $0}'

My best attempt is probably:

> awk -v n=3 '{ORS=" "}{while (count++<n) print} file.txt > newfile.txt
> cat newfile.txt
0.5 0.5 0.5

this skips line 2 and 3 though :frowning:
Anyone got the sneaky solution?

Hi, try:

awk -v n=3 '{for(i=2; i<=n; i++) $i=$1}1' file.txt > newfile.txt

The counter needs to be reset for every line..

Thank you very much!

In your approach,

  • you can't print every field without switching the ORS between space and line feed.
  • you need to reset the count variable (as Scrutinizer already pointed out)

Try also

awk -v n=3 '{while (NF++ < n) $NF = $1} 1' file

Thanks!
The ORS change was an attempt to avoid that the code threw me 4 rows instead of 1 as I wanted :slight_smile: