简体   繁体   中英

Sed to replace first two octets if they are 192.168

I need to use sed to replace first two octets with 212.15 if they match 192.168.

input="192.168.0.1 computer1.desktop"
input2="183.92.0.1 computer1.desktop"
# This should result in 
# result="212.15.0.1 newcomputer1.desktop"
echo $input | sed -e 's/192.168/212.15/g' | sed -e 's/computer1/newcomputer1/g'

And this part works fine. My problem is that the second sed should only be run if first regex matches the first two octets. They could both be probably be combined into one expression. Currently if I did this:

echo $input2 | | sed -e 's/192.168/212.15/g' | sed -e 's/computer1/newcomputer1/g'

# Then result wouldn't be accurate
# it would echo   "183.92.0.1 newcomputer1.desktop"

Any advice is appreciated.

Following sed command should do the two replacements over lines matching /192.168/

sed -e '/192.168/ { s/192.168/212.15/g; s/computer1/newcomputer1/g; }'

note that . matches any character and to ensure 192 is the first octet ^ can be used to match start of line.

sed -e '/^192\.168/ { s/^192\.168/212.15/; s/computer1/newcomputer1/; }'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM