如何用sed替换整条线?

时间:2022-05-13 16:51:02

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?

如何使用sed将所有这些行aaa=[something]替换为aaa=xxx ?

6 个解决方案

#1


125  

Try this:

试试这个:

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

#2


64  

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

您还可以使用sed的更改行来完成以下操作:

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.

这将通过并找到任何通过aaa= test的行,这意味着该行包含字母aaa=。然后用aaa=xxx替换整个直线。你可以添加一个^一开始的测试,以确保你只得到从aaa的线=但这取决于你。

#3


36  

Like this:

是这样的:

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

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

如果您想要保证aaa=在线的起点,请将其设置为:

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

#4


2  

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

如果你想使用awk,那么这个也可以。

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

#5


2  

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

#6


1  

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

#1


125  

Try this:

试试这个:

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

#2


64  

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

您还可以使用sed的更改行来完成以下操作:

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.

这将通过并找到任何通过aaa= test的行,这意味着该行包含字母aaa=。然后用aaa=xxx替换整个直线。你可以添加一个^一开始的测试,以确保你只得到从aaa的线=但这取决于你。

#3


36  

Like this:

是这样的:

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

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

如果您想要保证aaa=在线的起点,请将其设置为:

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

#4


2  

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

如果你想使用awk,那么这个也可以。

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

#5


2  

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

#6


1  

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