如何在Bash中替换=与&之间的内容为replaced?
Hey there! Let's figure out how to do that string replacement in Bash. Here's a straightforward approach using sed—it's perfect for this kind of text manipulation:
First, let's start with your original string. You can either pipe it directly into the command or store it in a variable. Here's the working command:
echo "test=test1&test2=test3&test3" | sed 's/=\([^&]*\)&/=replaced&/g'
Let me break down exactly what this does:
s/old/new/gis sed's global replace syntax—thegflag ensures we replace every matching occurrence, not just the first one.- The pattern
=\([^&]*\)&targets exactly the content you want to replace: it matches an equals sign=, followed by any sequence of characters that aren't an ampersand ([^&]*), then an ampersand&. This zeroes in on the "value" between=and&in each key-value pair. - We swap that matched pattern with
=replaced&, dropping in your desired replacement string instead of the original value.
If you'd rather work with a variable (handy for reuse), this works too:
original_str="test=test1&test2=test3&test3" modified_str=$(echo "$original_str" | sed 's/=\([^&]*\)&/=replaced&/g') echo "$modified_str"
Either way, you'll get the exact output you're after: test=replaced&test2=replaced&test3
内容的提问来源于stack exchange,提问作者Ineedhelp
相关产品推荐
相关产品推荐

