Issue
I have a line
echo "object smtp aaa smtp.asd.com server.smtp.com eq smtp"
object smtp aaa smtp.asd.com server.smtp.com eq smtp
and I need to replace the smtp with 25 but just were the smtp
is standing alone. The expected output should be
object 25 aaa smtp.asd.com server.smtp.com eq 25
It is not possible to use the \b or < > boundaries because there is a comma. I've tried to use
echo "object smtp aaa smtp.asd.com server.smtp.com eq 25" | sed -E 's/smtp[^.]?$/25/g'
object smtp aaa smtp.asd.com server.smtp.com eq 25
but it replaces just match at the end of the line. The
echo "object smtp aaa smtp.asd.com server.smtp.com eq smtp" | sed -E 's/smtp[^.]?( |$)/25/g'
object 25aaa smtp.asd.com server.smtp.com eq 25
replaces also the space. Does somebody has an idea how to solve the problem?
Solution
You may use this sed
:
s="object smtp aaa smtp.asd.com server.smtp.com eq smtp"
sed -E -e ':a' -e 's/(^|[[:blank:]])smtp([[:blank:]]|$)/\125\2/g;ta' <<< "$s"
object 25 aaa smtp.asd.com server.smtp.com eq 25
Here:
:a
: Sets labela
s/(^|[[:blank:]])smtp([[:blank:]]|$)/\125\2/g
replaces eachsmtp
with25
if it preceded by start position or whitespace and if it is followed by whitespace or end positionta
: Goes back to labela
if substitution is successful
Answered By - anubhava Answer Checked By - Senaida (WPSolving Volunteer)