问题描述
我看到了很多关于 sed
命令的问题,但没有一个与我的兄弟相匹配.
I saw so much questions about the sed
command but none match my dude.
我想替换包含模式的整行.
I want to substitute the entire line which contains a pattern.
我认为 sed
命令是最好的选择.我从这个 sed
命令开始,但不起作用
I think the sed
command is the best option. I started with this sed
command but doesn't work
sed -i 's/pattern/Substitution/' myfile.txt
在那之后,我使用另一个命令进行测试,但只替换模式,而不是整行.
After that i'm testing with this other command but only substitute the pattern, not the entire line.
echo "hello y luego bye" | sed "s|hello|adeu|g"
推荐答案
您需要匹配包含该模式的整行,然后替换.像这样使用它:
You need to match the whole line containing that pattern and then replace. Use it like this:
sed 's/^.*\bpattern\b.*$/Substitution/' file
我还为单词边界添加了 \b
以便您只匹配 pattern
但避免匹配 patterns
.
I also added \b
for word boundaries so that you only match pattern
but avoid matching patterns
.
说明: ^.*\bpattern\b.*$
我们用来确保整行匹配包含模式.^
是行开始,$
是行结束..*
匹配 0 个或多个长度的文本.所以^.*
匹配pattern
之前的所有文本,.*$
匹配pattern
之后的所有文本.
Explanation: ^.*\bpattern\b.*$
us used to make sure whole line is matched containing pattern. ^
is line start and $
is line end. .*
matches 0 or more length text. So ^.*
matches all the text before pattern
and .*$
matches all the text after pattern
.
使用 awk,您可以:
Using awk you can do:
awk '!/affraid/{print} /affraid/{print "Substitution"}' file
这篇关于sed:替换包含模式的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!