sed: replace a line containing a pattern

2019-04-13 08:31发布

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.

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"

1条回答
地球回转人心会变
2楼-- · 2019-04-13 09:09

You need to match the whole line containing that pattern and then replace. Use it like this:

sed 's/^.*\bpattern\b.*$/Substitution/' file

I also added \b for word boundaries so that you only match pattern but avoid matching patterns.

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.

Using awk you can do:

awk '!/affraid/{print} /affraid/{print "Substitution"}' file
查看更多
登录 后发表回答