0

I wanna print field (from 4th to the last field) as new line for each by inserting increasing arithmetically variable (from 5 to 25) after 3rd field in the text file.

Data format:

01.01.1995 01:00 1.0 1.2 2.5 3 4.8 5.2
31.01.1995 23.00 31.0 2.3 7.5 8.7 8.7 10

.

awk '{for(i=5;i<=25;i+=5) print $1,$2,$3,i,$(3+i/5)}'

Desired output:

01.01.1995 01.00 1.0 5 1.2
01.01.1995 01.00 1.0 10 2.5
01.01.1995 01.00 1.0 15 3
01.01.1995 01.00 1.0 20 4.8
01.01.1995 01.00 1.0 25 5.2
31.01.1995 23.00 31.0 5 2.3
31.01.1995 23.00 31.0 10 7.5
31.01.1995 23.00 31.0 15 8.7
31.01.1995 23.00 31.0 20 8.7
31.01.1995 23.00 31.0 25 10

Desired output 2:

01.01.1995 01.00 1.0 5 5.2
01.01.1995 01.00 1.0 10 4.8
01.01.1995 01.00 1.0 15 3
01.01.1995 01.00 1.0 20 2.5
01.01.1995 01.00 1.0 25 1.2
31.01.1995 23.00 31.0 5 10
31.01.1995 23.00 31.0 10 8.7
31.01.1995 23.00 31.0 15 8.7
31.01.1995 23.00 31.0 20 7.5
31.01.1995 23.00 31.0 25 2.3

So the first three field should be same.

2

There are a few obvious ways to do the arithmetic - for example

$ awk '{for(i=4;i<=NF;i++) print $1,$2,$3,5*(i-3),$i}' file
01.01.1995 01:00 1.0 5 1.2
01.01.1995 01:00 1.0 10 2.5
01.01.1995 01:00 1.0 15 3
01.01.1995 01:00 1.0 20 4.8
01.01.1995 01:00 1.0 25 5.2
31.01.1995 23.00 31.0 5 2.3
31.01.1995 23.00 31.0 10 7.5
31.01.1995 23.00 31.0 15 8.7
31.01.1995 23.00 31.0 20 8.7
31.01.1995 23.00 31.0 25 10

or

$ awk '{for(i=5;i<=25;i+=5) print $1,$2,$3,i,$(3+i/5)}' file
01.01.1995 01:00 1.0 5 1.2
01.01.1995 01:00 1.0 10 2.5
01.01.1995 01:00 1.0 15 3
01.01.1995 01:00 1.0 20 4.8
01.01.1995 01:00 1.0 25 5.2
31.01.1995 23.00 31.0 5 2.3
31.01.1995 23.00 31.0 10 7.5
31.01.1995 23.00 31.0 15 8.7
31.01.1995 23.00 31.0 20 8.7
31.01.1995 23.00 31.0 25 10

To reverse the order of the final field, start at NF and count down e.g.

awk '{for(i=5;i<=25;i+=5) print $1,$2,$3,i,$(NF+1-i/5)}'
  • So NF is a built-in variable that contains number of fields in the current record. Here, $NF gives last field in my view. I don't understand $i. I mean for any i variable $i =$5? – chess_freak Nov 20 '19 at 1:35
  • @chess_freak $i returns the value of the ith field so $4, $5 ... $NF as i is incremented in the loop – steeldriver Nov 20 '19 at 1:38
  • I got it. Thank you so much. – chess_freak Nov 20 '19 at 1:40
  • I was tried code like awk 'BEGIN {for(i=5;i<=25; i+=5) print $1,$2,$3,i,$i}' file. – chess_freak Nov 20 '19 at 1:48
  • @chess_freak a BEGIN block is executed before any lines of file are processed (hence $1,$2 and so on will be empty) – steeldriver Nov 20 '19 at 1:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.