1

I have a fixed-length data file where records are tagged (first 6 characters have a certain string that identifies the record) and I need to replace text from a specific line and a specific position on that line.

HEADER   123456
SHIPTO   CODE    123 LANE     HOUSTON    TX
ITEM     ACME BRICK

For example, I would like to replace the ship-to code in the above data. The data can be found in positions 10-17 of the ship-to record (line starts with "SHIPTO"). I'd like to use sed or awk (or other commands) but update the data with a single command line. If there is more than one SHIPTO line, I am ok with updating them all.

  • (1) I’m not sure what you mean by a “fixed-length file”. (2) Positions 10-17 of the ship-to record are CODE    . Is that really what you mean? – Scott May 7 at 21:30
2

Using sed:

$ sed -E '/^SHIPTO/ s/(.{9}).{8}/\1NuValue /' file
HEADER   123456
SHIPTO   NuValue 123 LANE     HOUSTON    TX
ITEM     ACME BRICK

How it works:

  • /^SHIPTO/

    This selects lines that start with SHIPTO. The substitute command which follows will only be applied to these lines.

  • s/(.{9}).{8}/\1NuValue /

    This matches the first 9+8 characters of the line and saves the first 9 characters of the line in group 1. These characters are replaced by group 1, \1, and your new value (which, to keep the format, should be 8 characters.

  • 1
    This is what I was looking for. Appreciate the help. – anterys May 8 at 14:25
1

Given the input file:

HEADER   123456
SHIPTO   CODE    123 LANE     HOUSTON    TX
ITEM     ACME BRICK

And the desire to change the field after 'CODE' where the first field is 'SHIPTO':

$ awk 'BEGIN { OFS = "\t" } $1 != "SHIPTO" { print } $1 == "SHIPTO" { $3="0000"; print }' input
HEADER   123456
SHIPTO  CODE    0000    LANE    HOUSTON TX
ITEM     ACME BRICK

If your fields are fixed-length and space-delimited and not tab delimited you can use formatted print strings (e. g. printf( "%20s\t" "$1" )).

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.