如何用Sed仅在匹配192.168前两段IP时执行双重替换?
Got it, let's sort out this sed issue so it only runs both replacements when the IP starts with 192.168. The problem with your original command is that the second sed call runs unconditionally—we need to tie both replacements directly to the IP match.
The Solution: Conditional Blocks in Sed
Sed lets you group commands to execute only when a specific pattern is found. Here's the adjusted command that does exactly what you need:
echo "$input" | sed -e '/192\.168/{s/192\.168/212\.15/g; s/computer1/newcomputer1/g}'
How It Works
/192\.168/: This is the address pattern—sed will only run the commands inside the curly braces{}if the line contains this exact string. We escape the dots\.because in regex, a plain.matches any character, and we want to match actual IP dots.s/192\.168/212\.15/g: Replaces all instances of192.168with212.15(escaped dots ensure we don't accidentally match other characters).s/computer1/newcomputer1/g: Replacescomputer1withnewcomputer1—but only if the initial IP pattern matched.
Testing the Cases
For your matching IP input:
input="192.168.0.1 computer1.desktop" echo "$input" | sed -e '/192\.168/{s/192\.168/212\.15/g; s/computer1/newcomputer1/g}'Output:
212.15.0.1 newcomputer1.desktop(exactly the expected result).For the non-matching IP input:
input2="183.92.0.1 computer1.desktop" echo "$input2" | sed -e '/192\.168/{s/192\.168/212\.15/g; s/computer1/newcomputer1/g}'Output:
183.92.0.1 computer1.desktop(no replacements run, which is what you wanted).
Bonus: More Precise IP Matching
If you want to ensure you only target 192.168 as the first two octets (not somewhere in the middle of an IP like 10.192.168.5), adjust the address pattern to anchor to the start of the line:
echo "$input" | sed -e '/^192\.168\./{s/192\.168/212\.15/g; s/computer1/newcomputer1/g}'
The ^ ensures the pattern only matches lines starting with 192.168., so you won't get false positives from IPs that include the sequence later on.
内容的提问来源于stack exchange,提问作者k4rli

