0 votes
in Education by (1.7m points)
I am trying to print a particular text using awk if string is empty. It works fine in the below case

[email protected]:~$ echo "" | awk '{if ($0=="") print "not playing"}'

not playing

but when I try to take a similar approach in the below case it didn't work

[email protected]:~$ mpc current | awk '{if ($0=="") print "not playing"}'

[email protected]:~$

I believe the output of mpc current if no song is playing is an empty string.

[email protected]:~$ mpc current

[email protected]:~$              #empty string

So, is my assumption of empty string wrong?

JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)

1 Answer

0 votes
by (1.7m points)
Apparently it prints nothing at all, not even a newline. Try this instead.

mpc current | awk '{ print } END { if (!NR) print "not playing" }'

This prints any output. If you don't want that, take out the { print }.

awk processes each line in turn, and then at EOF performs any END block. If there were no input lines, there will be an EOF right at the start, the variable NR will be zero, and so the END block will print the placeholder text. (I originally had a dedicated variable for this, but the built-in line number variable NR, as used in Bob Vale's answer, is decidedly more elegant. It is incremented for each input line that awk reads.)
...