1

I have a script that runs against a file and that takes arguments from a user and is sent through grep and awk to get the desired column. It will return multiple lines. What I want to do is read (or something of the like) through the output from grep|awk and run that through another script (./lookup). My question is how can I loop through each line and run what is on that line through my script inside the script. Hope this makes sense, I'm new to scripting and linux.

#!/bin/sh
x=$(grep "$*" "$c"|awk '{print $6}')
while read LINE   
do
./lookup $x
done

This seems to work but only for the first line of the output. It also requires me to hit enter to get the output from the ./lookup script. Any ideas or help? Thanks!

2 Answers 2

1

Pipe the output of grep and awk to the loop:

grep "$*" "$c" | awk '{print $6}' | while read LINE
do
    ./lookup "$LINE"
done

BTW, it's not usually necessary to use both grep and awk, since awk can do regexp matching. So you can write:

awk -v re="$*" '$0 ~ re {print $6}' "$c" | while ...

The -v option sets an awk variable, and the ~ operator performs regular expression matching. $0 refers to the whole input line.

Sign up to request clarification or add additional context in comments.

3 Comments

I think $* here is referring to the list of arguments, which will be interpolated by the shell
I didn't realize that, thank you! My reasoning for the use of $* was in case more than one word was entered as an argument against the main script (./find Los Angeles). Is there an easier way to make sure the whole string is passed?
Usually users are expected to enclose the argument in quotes, e.g. ./find 'Los Angeles'.
1

You could also use xargs instead of a loop

Also as barmar stated there is not need for grep.

awk -va="$*" '$0~a{print $6}' "$C" | xargs ./lookup

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.