如何在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 tellssedto 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.bakinstead—this createsmy.txt.bakwith the original content before changes are made.-e 's/my/our/gI': The first replacement rule:s/old/new/is the basicsedsubstitution syntaxgmeans "global"—replace every occurrence ofmyin a line, not just the first oneImakes the match case-insensitive, so it will replace both lowercasemyand uppercaseMy(which shows up in your original text). If you only want to target lowercasemy, just remove theI.
-e 's/xyz/abc/g': The second replacement rule, which globally replaces every instance ofxyzwithabc.
Example before/after:
Original
my.txtcontent:
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
相关产品推荐
相关产品推荐

