Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

awk problem

Status
Not open for further replies.

bobetko

Programmer
Jan 14, 2003
155
US
I have a line of text:

"my automobile is running well"

I want to use reg. expressions to match "auto" in automobile and to produce new variable which will have matching string.

I thought I can do something like this:
myvar = grep (/auto/, $2)

(after above myvar="auto")

but, it's not working.

Thanks for any help.
 
Since you know in advance, that your variable shall be 'auto' itself, an not the matching string, you can use the boolean return value of grep, to set myvar to auto:
Code:
myvar=""
grep auto $2 >/dev/null && myvar="auto"

seeking a job as java-programmer in Berlin:
 
Let me reformat my question....

Let's see example:

aaa john.red 55
bbb mary.blue 66
ccc iva.green 77

I want myvar to have anything from $2 that match /.+\./
(everything until first dot (john, mary and iva))

This is how I did it:
Code:
myvar = $2
sub(/\..+$/, "", myvar)  # I am deleting . (dot) and
                         # anything after that

So myvar would be: line1: john; line2: mary; line3: iva

Question is, can I do something like this with grep?

thx.
 
I don't think grep can do this, but sed:
Code:
echo "aaa john.red 55
bbb mary.blue 66
ccc iva.green 77
" | grep mary | sed 's/\..*//;s/.* //'
prints:

mary

If $2 already removed the leading 'bbb ', you would only need the first sed-command:
Code:
name=$(echo $2 | sed 's/\..*//')

seeking a job as java-programmer in Berlin:
 
Thanks Stefan,

Can you explain me this sintax a little bit?

name=$(echo $2 | sed 's/\..*//')

Why this: $(..........)
I mean, Why dollar sign in front of parentheses?

What does pipe "|" mean?

Thanks
 
The $(...) syntax is command substitution, just like the old grave accents method `...`, but cleaner. No separate process is created unless I/O is done.

A pipe is an interprocess channel that directs output of one command to the input of another.

The shell variable name is getting set with the output value of $(...).

But this is shell stuff, how is this relating to AWK?

# AWK
#
# Question 1:
# Just check if auto exists in $2 and set the variable.

{
if ( $2 ~ /auto/ ){
myvar="auto"
}
}

# Question 2:
{
match( $2, /[^\.]*/ )
myvar=substr( $2, 1, RLENGTH )
}

Cheers,
ND.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top