Search code examples
bashgrep

bash grep can return an empty space, how to substitute the empty space for a string?


I am attempting to grep an inbox for survey results, in which the subject will include the answer to the following question: "The answer to your question is ___"

The answered question will take the form of: "Subject: RE: The answer to your question is yes|no|' '"

I have tries the following in a bash script:

subject=$(cat /var/mail/incoming | grep '^Subject:' | cut  -d' ' -f 9)

I am expecting output similar to the following:

yes
no
no
yes

yes
no

In which there will be spaces where a non-answer occurred, and this is exactly what I see when I grep at the command line.

However, when I store the results in a var, the output is:

yes
no
no
yes
yes
no

How do I detect a space at the end of my grep command and replace it with "none"?

Desired output:

yes
no
no
yes
none
yes
no 

Solution

  • subject=$( awk '/^Subject:/ { print ($9 ? $9 : "none") }' /var/mail/incoming )
    

    For example:

    $ cat file
    Subject: RE: The answer to your question is yes
    Subject: RE: The answer to your question is no
    Subject: RE: The answer to your question is no
    Subject: RE: The answer to your question is yes
    Subject: RE: The answer to your question is
    Subject: RE: The answer to your question is yes
    Subject: RE: The answer to your question is no
    

    $ subject=$( awk '/^Subject:/ { print ($9 ? $9 : "none") }' file )
    

    $ echo "$subject"
    yes
    no
    no
    yes
    none
    yes
    no