Michael Gruenstaeudl
Michael Gruenstaeudl

Reputation: 1783

Awk - Writing length of subsequent line into line

Assume a text file that comprises alternating lines. Specifically, line 1 of each line pair starts with a "#", whereas the subsequent line of each line pair contains an alphanumeric string.

$ cat file
#Foo
1234567
#Bar
1234
#Baz
123456789

How do I automatically append the length of line 2 (as well as a keyword) to line 1 of each line pair? I believe that awk is the right choice for such an operation.

$ awk 'desired code' file
#Foo_Length7
1234567
#Bar_Length4
1234
#Baz_Length9
123456789

Here's my try, but I can't figure out what to substitute the length($0) with:

awk '{if ($1~/^#/) print $0"_Length"length($0); else print $0}' file

Upvotes: 3

Views: 63

Answers (3)

RavinderSingh13
RavinderSingh13

Reputation: 133518

Could you please try following. Using tac + awk combination here. Written on mobile couldn't test it yet should work though.

tac Input_file | 
awk '
NR%2!=0{
  len=length($0)
  print
  next
}
{
  print $0"_Length"len
  len=""
}' | 
tac

Explanation: Firstly using tac to print output in reverse which will help us to deal with data manipulation easily. Then with awk every odd number of line printing it and taking its length in len variable. Then on every even line printing current line with length of previous line. Once awk is done with its processing then again using tac to reverse the Input_file to make it in actual format.

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203502

$ awk '!(NR%2){print prev "_Length" length($0) ORS $0} {prev=$0}' file
#Foo_Length7
1234567
#Bar_Length4
1234
#Baz_Length9
123456789

You can replace !(NR%2) with !/^#/ or similar if you prefer.

Upvotes: 3

Cyrus
Cyrus

Reputation: 88601

With GNU awk:

awk '{first=$0; getline; print first "_length" length($0); print}' file

Output:

#Foo_length7
1234567
#Bar_length4
1234
#Baz_length9
123456789

From man awk:

getline: Set $0 from the next input record; set NF, NR, FNR, RT.

Upvotes: 2

Related Questions