linuxbashgrep

Use variable date (has dashes) to match an expression that is void of dashes


I am using exported variables saved in .bashrc that are dates for today and the next day to try to find matches for them in a webpage that I'm scraping for weather info. I had to save the date variables with separators (which are dashes) otherwise I couldn't export them to ~/.bashrc which a script updates automatically. The problem is that the dates I am trying to match them to from the webpage have spaces and the origin dates have dashes.

An example of an exported variable I have in ~/.bashrc:

export xdate=Fri-04-Oct

So if I try to match to Fri 04 Oct as it shows up on the webpage like this:

grep -F $(echo $xdate | tr '-' ' ')  casablanca_info

My result only matches on Fri which is why I used -F to try to match the whole string. I am new to programming and I know that I can use grep like grep -F 'Fri 04 Oct' without a hiccup but I can't match on the string when its in a variable and I remove the spaces.

I also tried to wrap $xdate in quotes like this

grep -F $(echo "$xdate" | tr '-' ' ')  casablanca_info

and I have tried changing it from how its saved in ~/.bashrc to

export xdate='Fri-04-Oct'

to force searching for the whole string including spaces and I am back to only returning Fri in my result.

The advice I received from shellcheck.net suggested to put quotes around $xdate or to include a shebang directive which I tried just for giggles but I have been testing this directly in the bash shell, to get it to work before storing the code in a script.


Solution

  • You need to put the command substitution in quotes so it will be a single argument:

    grep -F "$(echo $xdate | tr '-' ' ')" casablanca_info
    

    There's also no need to use command substitution, you can use the shell's built-in character replacement operation:

    grep -F "${xdate//-/ }" casablanca_info
    

    You could just store the date with spaces in the variable, as long as you quote it:

    xdate='Fri 04 Oct'
    grep -F "$xdate" casablanca_info
    

    In general you should always quote variables and command substitutions, unless you specifically need to perform word splitting and globbing on the result.