You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Sed仅在匹配192.168前两段IP时执行双重替换?

Fixing Conditional Sed Replacements

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 of 192.168 with 212.15 (escaped dots ensure we don't accidentally match other characters).
  • s/computer1/newcomputer1/g: Replaces computer1 with newcomputer1—but only if the initial IP pattern matched.

Testing the Cases

  1. 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).

  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:21:24