ChatGPT解决这个技术问题 Extra ChatGPT

How to replace a whole line with sed?

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?

Is [something else] the literal text, or is that just a placeholder? What is the possible format of the thing after the equals sign?
that is more of a regex question not a sed question.

J
John Doyle

Try this:

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

Force of habit, it can be ignored in this case - it's used as a global replacement for the line to replace each match rather than just the first. In this case though only the first will be matched because of the .*.
Michael J. Barber, g replace all the instance of regexp with replacement
Add -i to change the file in place
M
Mr. T

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.


OS X's 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'.
Here's and example in the sed documentation of the change/replace feature that @Mr. T is talking about.
This is the closest to actually doing what was asked... (But Lri's version is needed for portability)
What I like about it: if you match a range of lines, the c will replace the entire range with just a single line: '/garbage_start/,/garbage_stop/c\[Garbage skipped]' The s doesn't do that.
M
Michael J. Barber

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/'

What if I want to replace with aaa='xxxx'. I tried escaping like sed 's/aaa=.*/aaa=\'xxx\'/' but that opens up a > prompt in a new line...
Change the single quotes to double quotes like sed "s/aaa=.*/aaa='xxx'/g"
V
Vijay
sed -i.bak 's/\(aaa=\).*/\1"xxx"/g' your_file

j
jaypal singh

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

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

How does this check for "aaa" pattern?
p
potong

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

I don't think an explicit check for bbb, ccc, and ddd is quite what the OP had in mind.