How do you preserve the max length of a line after replacing a specific value?

I'm new with scripting and I can't seem to figure out what I should do to get the output that I want.

My file content would be below.

ID2|ID3       |ID4|ID5       |

I'm trying to replace the field of ID3 which has a fixed length of 10 characters, for each entry I have placed on a .txt file and placing the value on variable called "NEW".

Here is my sed command.

sed -i 's/ID3/$NEW/g' TESTFILE_TEST

Is there anyway to maintain the 10 characters on the field for each entry it reads on my .txt file?

Not sure I understand. You can't preserve a 10 char length for a field that is three (four if you count the space) chars in length. What be the length of $NEW ?

Hi RudiC,

Apologies I updated my question.

The value that will be placed on $NEW will not be greater than 10, it could be a character value of 5 but the segment where ID3 is placed will still remain 10 characters. Including the spaces.

Please edit your post #1 and wrap your sample in CODE tags! (Click on the symbol that looks like </> )

Try (assuming you want to fill up with spaces)

$ SPC="          "
$ sed  "s/ID3/$NEW${SPC:${#NEW}}/g" file

Include the existing trailing spaces in order to replace(=remove) them:

s/ID3 */$NEW${SPC:${#NEW}}/

A variant with printf:

sed -i "s/ID3 */$(printf "%-10s" "$NEW")/" TESTFILE_TEST
1 Like