How to replace a whole line with sed?

RegexSed

Regex Problem Overview


Suppose I have a file with lines

aaa=bbb

Now I would like to replace them with:

aaa=xxx

I can do that as follows:

sed "s/aaa=bbb/aaa=xxx/g"

Now I have a file with a few lines as follows:

aaa=bbb
aaa=ccc
aaa=ddd
aaa=[something else]

How can I replace all this lines aaa=[something] with aaa=xxx using sed?

Regex Solutions


Solution 1 - Regex

Try this:

sed "s/aaa=.*/aaa=xxx/g"

Solution 2 - Regex

You can also use sed's change line to accomplish this:

sed -i "/aaa=/c\aaa=xxx" your_file_here

This will go through and find any lines that pass the aaa= test, which means that the line contains the letters aaa=. Then it replaces the entire line with aaa=xxx. You can add a ^ at the beginning of the test to make sure you only get the lines that start with aaa= but that's up to you.

Solution 3 - Regex

Like this:

sed 's/aaa=.*/aaa=xxx/'

If you want to guarantee that the aaa= is at the start of the line, make it:

sed 's/^aaa=.*/aaa=xxx/'

Solution 4 - Regex

sed -i.bak 's/\(aaa=\).*/\1"xxx"/g' your_file

Solution 5 - Regex

If you would like to use awk then this would work too

awk -F= '{$2="xxx";print}' OFS="\=" filename

Solution 6 - Regex

This might work for you:

cat <<! | sed '/aaa=\(bbb\|ccc\|ddd\)/!s/\(aaa=\).*/\1xxx/'
> aaa=bbb
> aaa=ccc
> aaa=ddd
> aaa=[something else]
!
aaa=bbb
aaa=ccc
aaa=ddd
aaa=xxx

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichaelView Question on Stackoverflow
Solution 1 - RegexJohn DoyleView Answer on Stackoverflow
Solution 2 - RegexMr. TView Answer on Stackoverflow
Solution 3 - RegexMichael J. BarberView Answer on Stackoverflow
Solution 4 - RegexVijayView Answer on Stackoverflow
Solution 5 - Regexjaypal singhView Answer on Stackoverflow
Solution 6 - RegexpotongView Answer on Stackoverflow