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

如何在Linux/Mac系统中用单行命令批量替换文件中的多段文本?

Single Command to Replace Text in my.txt

Hey there! Let's get this text replacement sorted with a single line of sed—it's perfect for quick in-place edits like this. Here's the command you need:

sed -i -e 's/my/our/gI' -e 's/xyz/abc/g' my.txt

Breakdown of the command:

  • -i: This tells sed to modify the file in-place (no need to redirect output to a new file). If you want to keep a backup of the original, use -i.bak instead—this creates my.txt.bak with the original content before changes are made.
  • -e 's/my/our/gI': The first replacement rule:
    • s/old/new/ is the basic sed substitution syntax
    • g means "global"—replace every occurrence of my in a line, not just the first one
    • I makes the match case-insensitive, so it will replace both lowercase my and uppercase My (which shows up in your original text). If you only want to target lowercase my, just remove the I.
  • -e 's/xyz/abc/g': The second replacement rule, which globally replaces every instance of xyz with abc.

Example before/after:

Original my.txt content:
This is my xyz. My color is white.

After running the command:
This is our abc. Our color is white.

Note for macOS users:

If you're on macOS, the sed syntax is a bit different—you need to add an empty string after -i like this:

sed -i '' -e 's/my/our/gI' -e 's/xyz/abc/g' my.txt

内容的提问来源于stack exchange,提问作者user1187968

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:54:04