-4

How can i set a variable using the while loop variable and pipe to awk?

here is my current code, i have tried multiple ways, and i can not seem to find an answer.

while IFS= read -r var
do
MyNewVariable= ($var | awk '{print $1}')

I know i am getting the correct lines, but am getting an incorrect command at the new variable line. is this possible?

  • Try pasting your code into shellcheck.net and then come back here if you still have questions after you've fixed the obvious issue(s). – roaima Dec 12 '17 at 21:38
  • I only showed important pieces of code. the problem is with the last line shown. It does not like setting MyNewVariable to be equal to an expression using var in any way. I was able to do it using an array – Jason V Dec 14 '17 at 3:50
2

It's very unclear what you're asking here.. but I'll make a run at a number of things. Please revise your question keeping the following in mind.

First.. the portion that reads

$var | awk '{print $1}'

What that is going to to is interpret the contents of value "var" and execute that command, pipe it to awk, and print the first work. Since it's unlikely that what is in $var is a valid command, that is likely to fail

The correct syntax of what you're attempting is either:

command | while IFS= read -r var; do
    echo $var
done

If you're going to work on the output of a command, or:

while IFS= read -r var; do
    echo $var
done < input_file

If you're going to work on the contents of a file.

But really, wrapping the "while" structure around is pointless, because you could just as easily do:

command | awk '{ print $1 }'

or

awk '{ print $1 }' < file

If you want to set a variable to use within awk, you can do

awk -v foo=$var '{ print foo }'

You can also set IFS within awk

awk 'BEGIN { FS=":" } { print $1 }'
  • worse? how? at least it's a complete where loop, whereas OP's was not. it was intended to at least show the correct usage of the variable that caught the line – Erik Dec 12 '17 at 21:47
  • Again.. it was intended to be GENERAL.. but I'd that more to your liking? – Erik Dec 12 '17 at 22:06
  • You're right, I did.. fixed – Erik Dec 12 '17 at 22:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.