1828355 Members
3808 Online
109976 Solutions
New Discussion

awk

 
SOLVED
Go to solution
maliaka
Advisor

awk

awk '$1!~/^[0-9]+$/&&$2!~/^[a-zA-Z0-9]+$/{print;exit 1}' tmp.txt

I've got this to work good but the problem is that it's not returning 1 if I have only characters in both fields. I need it to return a vaule of 1 when the first two fields are characters and when the first field is characters and the second field is numbers?

example:

myredcar mybluecar
mycar 192.168.1.10

it's not returning a value of 1 for the first line but it does work for the second line.
7 REPLIES 7
Peter Godron
Honored Contributor

Re: awk

Hi,
have you tried the code without the 'exit 1' ?
Can you please specify the exact requirements.
James R. Ferguson
Acclaimed Contributor

Re: awk

Hi:

Perhaps:

# awk '$1!~/^[0-9]+$/||$2~/^[0-9]+$/{print;exit 1}' tmp.txt

Regards!

...JRF...
maliaka
Advisor

Re: awk

I tried that but it returns 1 with all of the lines.

Here is my requirements:

cat f1.txt
myredcar mybluecar
mycar 192.168.1.10
192.168.1.1 192.168.1.2
192.168.1.3

It should return a failure status for all of the above lines and return a successful status for the following line whenever they exist in the file f1.txt

192.168.1.4 host100

The lines however, should not be less than or exceed 2 fields.

awk '{NF ==2}' f1.txt, I would like to add this one to the same awk statement so that I'll have only one line of awk commands.

James R. Ferguson
Acclaimed Contributor
Solution

Re: awk

Hi (again):

OK, so lets consider only the initial character in each field:

# awk 'NF!=2||$1!~/^[0-9]/||$2~/^[0-9]/{print;exit 1}' file

Regards!

...JRF...
maliaka
Advisor

Re: awk

James

One thing though, it should also fail with the following:

1111111111 myhost100

Notice that the first field doesn't have dots.
Dennis Handly
Acclaimed Contributor

Re: awk

>I would like to add this one to the same awk statement so that I'll have only one line of awk commands.

Do you really want something that confusing?

>One thing though, it should also fail with the following:
1111111111 myhost100
>Notice that the first field doesn't have dots.

Perhaps you need to write a program in awk. I suppose you could have a ERE that would have 3 dots in it, otherwise you could put more checks in your awk script.
awk '$1 !~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ || $2 !~ /^[a-zA-Z0-9]+$/ {print;exit 1}'

Above it looks for 3 ".". (I couldn't use the \{3\} syntax to have groups of "###.".)
maliaka
Advisor

Re: awk

James and Dennis are both good solutions.
Thanks to both of you.