admin管理员组

文章数量:1123230

I have a text file with the following output.

good,bad,ugly
good,good,ugly
good,good,good,bad,ugly
good,bad,bad
bad,bad,bad,bad,good
bad,ugly,good
bad,good,bad
good,good,good,good,bad
ugly,bad,good
bad,bad,bad,good,ugly

I only want to list lines that have a single occurance of ugly and bad. Any line with multiple bads need to be excluded.

I've tried to use the following but it's still listing lines with multiple bads. grep -E "bad|ugly" file.txt | grep -v "('bad').*\1"

I have a text file with the following output.

good,bad,ugly
good,good,ugly
good,good,good,bad,ugly
good,bad,bad
bad,bad,bad,bad,good
bad,ugly,good
bad,good,bad
good,good,good,good,bad
ugly,bad,good
bad,bad,bad,good,ugly

I only want to list lines that have a single occurance of ugly and bad. Any line with multiple bads need to be excluded.

I've tried to use the following but it's still listing lines with multiple bads. grep -E "bad|ugly" file.txt | grep -v "('bad').*\1"

Share Improve this question edited 8 hours ago Paolo 25.8k8 gold badges48 silver badges85 bronze badges asked 8 hours ago Chase BrandChase Brand 1 New contributor Chase Brand is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 2
  • 1 Asking "how to do X with tool Y" is generally not a good idea. If the question is "how do I drive a screw with a hammer", the correct answer is "you don't". You want to know how to to do a certain task, and grep is the wrong tool. By insisting on using grep, you restrict the value of the answers you will get. – William Pursell Commented 8 hours ago
  • 1 Do you want to see a line like "badbadgood" in the output? There seems to be an implied structure (ie, csv) in your data that you have not specified. Should "badbad,bad,good" be in the output? or "bad,mybad,good"? – William Pursell Commented 8 hours ago
Add a comment  | 

2 Answers 2

Reset to default 2

Your current approach using grep -E "bad|ugly" matches any line with either "bad" OR "ugly", and the back-reference attempt isn't quite working.

grep -E 'bad.*ugly|ugly.*bad' file.txt | grep -v 'bad.*bad'

This will give you:

good,bad,ugly
good,good,ugly,bad
ugly,bad,good

You have to use -P (for Perl-compatible regular expressions) for back-references.

grep -E "bad|ugly" file.txt | grep -Pv "(bad).*\1"

本文标签: linuxHow to exclude lines with duplicate strings using grepStack Overflow