How to feed the results of date command into grep to filter results of another command
Solution 1
In bash, just use something like alertcommand | grep $(date +"%m/%d")
$()
executes a command in a subshell and returns the output of the command as string. Alternatively you can enclose the command with backticks to the same effect.
Solution 2
You could simply assign the output of your date command to another variable, and use that as an argument:
myDateVariable=`date +"%m/%d"`
alertcommand | grep $myDateVariable
This way, you could re-use the date value in the future and also debug any intermediate steps
Related videos on Youtube
MaQleod
I'm a Software Quality Principal Engineer that specializes in Networking and hardware (with a strong emphasis on Unix/Linux systems). My background is in Telecom and Network troubleshooting. I am proficient in both Ethernet and Infiniband standards. I code primarily with Python, Autoit, C and and SQL in my spare time, but I like to occasionally tinker in other languages. My degree is in Classical Numismatics and Archaeology. I also keep a blog on investing. profile for MaQleod on Stack Exchange, a network of free, community-driven Q&A sites http://stackexchange.com/users/flair/343e8ac1ebe84dacb26151af03317dcd.png
Updated on September 18, 2022Comments
-
MaQleod almost 2 years
I need to use the result of a formatted date command (date +"%m/%d") as the grep filter to filter the results of another command that will display alerts on a system so that I only see alerts from the given day.
Lets say alertcommand gives the alert readout in the console. I know I can do
alertcommand | grep 8/10
to get the logs from today, but I want to be able to feeddate +"%m/%d"
into that so that I don't have to specify the date each time I run it, but I can't figure out how to link it into one single command (preferably without having to create temp files or anything as this will be run on customer hardware).I looked at this question that was similar, but couldn't figure out how to make it work the same way.
-
MaQleod almost 13 yearsThis worked, seems I was just missing the format of how to write it out from the other question I noted. I prefer to use $() as it is the more modern implementation.
-
Sudipta Chatterjee almost 13 yearsYou can always separate them via a semicolon. For example, you could say
myDateVariable=`date +"%m/%d"`; alertcommand | grep $myDateVariable
-
clerksx over 12 years
csh
is harmful, stop using it. faqs.org/faqs/unix-faq/shell/csh-whynot