I need to replace a column value in a fixed width file which is having unknown value in one of the columns and need to replace the column value with some column value in the same line.

      A      B      C      D        E    F      G     H     I     J      K     L      M      N
ex: 123908 456567 675674 0000000x 45678 09756 125678 45678 09756 125678 45678 09756 125678 45678 09756  

here instead of 0000000x (column D), I need to replace it with 125678 (column G).

I have tried:

awk 'BEGIN{FS=OFS=""}{f=0;for(i=292;i<=300;i++){if($i!~/0000000X/){f=1}};if(f) {for(i=292;i<=300;i++){$i=2}};print }'

This command is changing for the respective column in all rows. But I need to be changed for the particular column having the 0000000x value.

  • Why not change the column the very moment you identify it (i.e. in the first for loop)? You don't use the G column in your one liner. How do you determine the G column?
    – RudiC
    Feb 16, 2022 at 14:53
  • 2
    Do you need to replace 0000000x because it has that value in column D or do you need to change whatever value is in column D? Setting FS="" is undefined behavior so it'll do different things in different awks but none of them will do anything you want to do. You say your input is fixed width fields but then you show input that has space-separated fields and you don't tell us the start char pos and length of "column D" or "column G" if the input really is fixed width so it's hard to know how to help you.
    – Ed Morton
    Feb 16, 2022 at 15:08

1 Answer 1


Given this input:

$ cat file
a X c D e X f
a B c D e X f

It sounds like you're trying to do either this:

$ awk '$2=="X"{$2=$4} 1' file
a D c D e X f
a B c D e X f

or this:

$ awk '{for (i=1;i<=NF;i++) if ($i=="X") $i=$4} 1' file
a D c D e D f
a B c D e D f

If it's neither of those then please edit your question to clarify your requirements and provide a more truly representative example.

You must log in to answer this question.

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