Search and replace value based on certain conditions in a fixed width file

Hi Forum.

I tried searching for a solution using the internet search but I haven't been able to find any solution for what I'm trying to accomplish.

I have a fixed width column file where I need to search for any occurrences of "D0" in col pos.#1-2, 10-11, 20-21 and replaced it with "XD".

Input File
D00000030D002002000D082143900000402940182900614001523024571208
Output File
XD0000030XD02002000XD82143900000402940182900614001523024571208

I have tried the following so far but it doesn't work as expected:

awk 'BEGIN {OFS=FS} substr($0,1,2) == "D0" {substr($0,1,2) = "XD"}; 1' file1.txt

Thanks
Paul

In awk , the substr() function is used to extract (partial) strings, but can't be assigned to. You'd need to either break up the line, with substr() s, and reassemble with the new data, or use the sub() / gsub() functions.
Would sed do as well? Try

sed -r 's/^D0/XD/; s/^(.{9})D0/\1XD/; s/^(.{19})D0/\1XD/;' file
1 Like

Is your awk actually gawk ?
You could use gawk's FIELDWIDTHS var to break up a string into pieces.