0

Observed there is a position changed for string datatype after count was appended at the end.

       awk '$2=="H" {x = substr($3,1,4); next} {$(NF+1) = x} 1'

Input:

12      H   0003A 
12305245D   2500 AB   5454 87870001A 
12305245D   2500 ABC  5454 87870002A 
12305245D   2500 ABCD 5454 87870003A

Expected Output :

12      H   0003A 
12305245D   2500 AB   5454 87870001A 0003 
12305245D   2500 ABC  5454 87870002A 0003
12305245D   2500 ABCD 5454 87870003A 0003

Actual Output:

12      H   0003A 
12305245D   2500 AB 5454 87870001A 0003
12305245D   2500 ABC 5454 87870002A 0003
12305245D   2500 ABCD 5454 87870003A 0003

1 Answer 1

1

By setting the field separator to an empty string with -F '', you are telling awk to treat each character as a separate field. So $ is never equal to H (and $3 can never have the indicated substring). Instead, use the default (whitespace) separator.

Also you seem to want to add the substring as a separate delimited field print $0, x rather than appending it as a string ($0 = $0 x)

$ awk '$2=="H" {x = substr($3,1,4)} $2!="H" {print $0, x}' input
12305245D   2500 AB   5454 87870001A  0003
12305245D   2500 ABC  5454 87870002A  0003
12305245D   2500 ABCD 5454 87870003A 0003

A simplified version:

$ awk '$2=="H" {x = substr($3,1,4); next} {print $0, x}' input
12305245D   2500 AB   5454 87870001A  0003
12305245D   2500 ABC  5454 87870002A  0003
12305245D   2500 ABCD 5454 87870003A 0003

NOTE these answers strictly retain the position of the input fields: the variable spacing of the final column is a result of the variable amount of trailing whitespace in your posted input.

2
  • Thanks for the command. I have faced another issue whenever string datatype present and UNIX command changed the position of fixed width file. Any way to retain the position of string types?
    – Chakkara
    Jul 2, 2018 at 15:26
  • @Chakkara please see updated answer Jul 2, 2018 at 15:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .