Home > Software engineering >  sed backreference regex to support spaces and tabs
sed backreference regex to support spaces and tabs

Time:02-03

Im am trying to write a small sed substitution one liner to add a hostname to an existing entry in an /etc/hosts file, so for example, this line

10.80.0.4 host.compute.internal

I want to inject othername into the line like this

10.80.0.4 othername host.compute.internal

Ive managed to put the following together using backreferences and it works fine as long as the items are separated by a space

cat /etc/hosts |
sed  's/\(^.\ \) \(.\ compute.internal\)/\1 othername \2/g'

however..I need this regex to also support Tab separated items as well, Does anyone have any ideas how i can amend the above to support tabs and spaces?

any help would be greatly appreciated thanks

CodePudding user response:

This may do what you want:

sed -E 's/(^. )[[:blank:]](. compute.internal)/\1 othername \2/'

See Character Classes and Bracket Expressions (sed, a stream editor) for an explanation of [[:blank:]].

  • Related