2

I want to add two columns to a file with ~10,000 columns. I want to insert as the first column the nr 22 on each row. Then I want the original first column as the second column, then as the third column I want to insert the line nr (NR), and after that I want the rest of the original columns to be printed. I thought I could do that with the following awk line:

awk '{print 22, $1, NR; for(i=2;i<=NF;++i) print $i}' file

It prints the first three columns (22, $1, NR) well, but after that, there is a new line started for each value, so the file is printed like this:

22 $1 NR
$2
$3
$4
etc...

instead of:

22 $1 NR $2 $3 $4 etc...

What did I do wrong?

2 Answers 2

4

How about using printf instead since print adds a newline.

awk '{printf("%d, %d, %d, ", 22, $1, NR); for(i=2;i<=NF;++i) printf("%d, ", i)}' file

Or you can play with the ORS and OFS, the Output Record Separator and the Output Field Separator. Normally you add those in a BEGIN statement like this:

awk 'BEGIN { ORS = " " } {print 22, $1, NR; for(i=2;i<=NF;++i) print $i}{print "\n"}' file 

Note that an extra printf "\n" is needed, else everything ends up on one line...

Read more in gawk manual output separators

Sign up to request clarification or add additional context in comments.

Comments

1

For more precise control over the output format than what is provided by print(which print a newline by default), use printf.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.