Inian
Inian

Reputation: 85825

Need to make awk suppress the output to stdout

I wanted to use awk for a solution of mine to parse records row-wise (looping upto max elements (upto NF)) and then store some of the fields in a bash variable. I was able to get the records I need, but couldn't avoid awk printing its own output to stdout.

This is the example I adopted.

newvar=$(echo "Hello, this is a sentence with a few words." | awk '{ s = ""; for (i = 0; i <= 5; i++) s = s $i " "; print s }'

I wanted to store the words Hello, this is a sentence in the bash variable newvar. Though there are more efficient ways to do this, for the moment consider the way to do with awk only.

This is storing the output as the one below in the variable

Hello, this is a sentence with a few words. Hello, this is a sentence

I tried suppressing the stdout to the null by doing 1>&- as,

$ newvar=$(echo "Hello, this is a sentence with a few words." | awk '{ s = ""; for (i = 0; i <= 5; i++) s = s $i " "; print s }'  1>&- )

Got an ugly error saying,

awk: (FILENAME=- FNR=1) warning: error writing standard output (Bad file descriptor)

Haven't been able to find a decent answer here nor anywhere on how to do this. Is this even possible with awk? Duplication of the exact post if found is appreciated too!

Upvotes: 2

Views: 2571

Answers (1)

fedorqui
fedorqui

Reputation: 290185

The problem here is that you are looping from 0 to 5. This means that you are storing $0 in the variable s and, as you know, $0 contains the full record. This means you are storing the full record followed by the 5 first fields.

So just loop from 1 to 5:

$ awk '{s = ""; for (i = 1; i <= 5; i++) s = s $i " "; print s }' <<< "Hello, this is a sentence with a few words."
Hello, this is a sentence 

Note by the way that it is not necessary to set s as "" in the beginning: any variable does get set when you start using it. Although you may be using this because you have multiple lines, so that you need to reset its value after every record.

This being said, if you just want to print the first 5 words, use cut:

$ cut -d' ' -f-5 <<< "Hello, this is a sentence with a few words."Hello, this is a sentence

Upvotes: 4

Related Questions