Issue
In a text file test.txt are many lines of text, of which I want to extract a single line matching:
blabla 28.40.00 blabla
I would like to replace the first digit of the middle number (in this case 4) by three. That is, no matter what the middle number is (40, 41, 52, 63 etc), I would like it to be replaced by a number starting with 3 (40 becomes 30, 41 becomes 31, 52 becomes 32, 63 becomes 33 etc).
The following line matches the middle number and replaces it with the alphabet a
:
cat test.txt |awk '/blabla/'|sed -E s_[[:digit:]][[:digit:]]_3_2
output: blabla 28.3.00 blabla
But when I want to replace only the first digit, sed doesn't work:
cat test.txt |awk '/blabla/'|sed -E s_[[:digit:]]\([[:digit:]]\)1_3\1_2
output: blabla 28.40.00 blabla
What am I doing wrong?
Solution
To always replace the third digit in the line:
$ echo 'blabla 28.40.00 blabla' | sed 's/[0-9]/3/3'
blabla 28.30.00 blabla
If the number before the .
can have more than 2 digits, here's one workaround:
$ echo 'blabla 528.40.00 blabla' | sed 's/\.[0-9]/.3/'
blabla 528.30.00 blabla
In your second attempt, you should quote the command and use unescaped parenthesis. You also seem to have an extra 1
after the capture group.
$ echo 'blabla 28.40.00 blabla' | sed -E 's_[[:digit:]]([[:digit:]])_3\1_2'
blabla 28.30.00 blabla
Also, you don't need awk
in this case. You can add filter in sed
as well:
$ echo 'blabla 28.40.00 blabla' | sed -E '/blabla/ s_[[:digit:]]([[:digit:]])_3\1_2'
blabla 28.30.00 blabla
Answered By - Sundeep Answer Checked By - Terry (WPSolving Volunteer)