Reputation: 47
I'm attempting to print lines that have only one t, or only one T, where anything else is fine. IE no lines that have no t's, no lines with 2 or more t's, and no lines that have 1 T and 1 t.
I'm trying :
egrep '[tT]{1,1}$' filename
and this is showing the following lines:
nopqrstuvwxyz
letters (this line is the one that should not be here)
The price is *$2*
one two three (this line should not be here either)
ONE TWO
THREE
These are all the lines that have a t or T in them in the file. How should I be going about this?
Upvotes: 1
Views: 62
Reputation: 8721
If you are considering Perl, below would work
> cat ip.txt
foobaz
nopqrstuvwxyz
letters
The price is *$2*
one two three
ONE TWO
THREE
1234
> perl -ne ' $x++ for(/t/ig);print if $x==1 ; $x=0 ' ip.txt
nopqrstuvwxyz
The price is *$2*
ONE TWO
THREE
>
If you need to grep with exact 2 matches - just change the condition to $x==2.
Upvotes: 0
Reputation: 23677
$ cat ip.txt
foobaz
nopqrstuvwxyz
letters
The price is *$2*
one two three
ONE TWO
THREE
1234
$ grep -ix '[^t]*t[^t]*' ip.txt
nopqrstuvwxyz
The price is *$2*
ONE TWO
THREE
-i
to ignore case-x
to match whole line only
grep
matches anywhere in the line-x
, you'd need grep -i '^[^t]*t[^t]*$'
[^t]*
any character other than t
(because of -i
option, T
would also be not matched)
You can also use awk
here:
$ awk -F'[tT]' 'NF==2' ip.txt
nopqrstuvwxyz
The price is *$2*
ONE TWO
THREE
-F'[tT]'
specify t
or T
as field separatorNF==2
print if line contains two fields, i.e if the line had one t
or T
Upvotes: 3