Pipe to awk to variable

Hi!

If I'm trying something like:

echo "hello world" | myvar=`awk -F "world" '{print $1}'`
echo $myvar

myvar is always empty :confused:

I googled for houres now and don't understand why it isn't working...
Trying it in normal bash.

Can someone explain it to me so I can say "Of course! Stupid me..." ? :smiley:

Thanks!

I don't understand what you are trying to achieve with that command ...

Getting "hello" into myvar

myvar="hello"
echo $myvar

would give me the result I want to achieve

Edit:

echo "hello world" | awk -F "world" '{print $1}'

Would give me "hello", I just want to put that into my variable

I'm still not sure, but it seems that you want to write something like this:

myvar=`echo "hello world" | awk -F "world" '{print $1}'`

I'm sure you'll get a better solution if you post more details ...

1 Like

That's exactly what I wanted^^

I knew it would be simple :wall:

Thanks!

In some shells:

read VAR G <<<"hello world"

puts the variable into VAR without needing to call awk at all, which makes it hundreds of times faster.

But I need awk to cut the string (since cut can only handle 1 char)

:confused: I didn't even mention cut.

What makes you think you need awk to cut the string? There's powerful shell builtins to handle things like that -- like read, which I illustrated. Running awk, cut, sed, grep etc. in backticks all the time to do one line is probably a mistake.

Perhaps you should post your entire script? I suspect there's lots that can be optimized. Please also explain what your system is and what shell you use.

I'm used to use "awk -F "[pattern]" '{print $[field]}'", it's easy to use and does it's job well. What else could I use?
I only wanted to make a quick little script that shows me how far cp is.
While cp is running, it checks with du the size of the two files and gives me a percentage.
Nothing fancy, and I know that rsync can do that by it's own, but I just tried to maybe learn a bit more by doing it myself. And I just learned something right now, so it was worth it :slight_smile: