Thursday, February 3, 2022

[SOLVED] How can I replace a specific character in a file where it's position changes in bash command line or script?

Issue

I have the following file:

2020-01-27 19:43:57.00 C M -8.5 0.2 0 4 81 -2.9 000 0 0 00020 043857.82219 3 1 1 1 1 1

The character "3" that I need to change is bolded and italicized. The value of this character is dynamic, but always a single digit. I have tried a few things using sed but I can't come up with a way to account for the character changing position due to additional characters being added before that position.

This character is always at the same position from the END of the line, but not from the beginning. Meaning, the content to the left of this character may change and it may be longer, but this is always the 11th character and 6th digit from the end. It is easy to devise a way to cut it, or find it using tail, but I can't devise a way to replace it.

To be clear, the single digit character in question will always be replaced with another single digit character.


Solution

With GNU awk

$ cat file
2020-01-27 19:43:57.00 C M -8.5 0.2 0 4 81 -2.9 000 0 0 00020 043857.82219 3 1 1 1 1 1

$ gawk -i inplace -v new=9 'NF {$(NF-5) = new} 1' file

$ cat file
2020-01-27 19:43:57.00 C M -8.5 0.2 0 4 81 -2.9 000 0 0 00020 043857.82219 9 1 1 1 1 1

Where:

  • NF {$(NF-5) = new} means, when the line is not empty, replace the 6th-last field with the new value (9).
  • 1 means print every record.


Answered By - glenn jackman
Answer Checked By - Candace Johnson (WPSolving Volunteer)