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 these lines aaa=[something]
with aaa=xxx
using sed?
[something else]
the literal text, or is that just a placeholder? What is the possible format of the thing after the equals sign?
Try this:
sed "s/aaa=.*/aaa=xxx/g"
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.
sed
requires c
to be followed by a backslash and a newline, and it doesn't append a newline to the inserted text, but you can use for example $'/aaa=/c\\\naaa=xxx\n'
.
c
will replace the entire range with just a single line: '/garbage_start/,/garbage_stop/c\[Garbage skipped]'
The s
doesn't do that.
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/'
sed 's/aaa=.*/aaa=\'xxx\'/'
but that opens up a >
prompt in a new line...
sed "s/aaa=.*/aaa='xxx'/g"
sed -i.bak 's/\(aaa=\).*/\1"xxx"/g' your_file
If you would like to use awk
then this would work too
awk -F= '{$2="xxx";print}' OFS="\=" filename
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
bbb
, ccc
, and ddd
is quite what the OP had in mind.
Success story sharing
.*
.g
replace all the instance of regexp with replacement-i
to change the file in place