LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   awk andvariable interpolation (https://www.linuxquestions.org/questions/linux-newbie-8/awk-andvariable-interpolation-908876/)

casperdaghost 10-18-2011 10:12 PM

awk andvariable interpolation
 
Is there a way that I can interpolate variable in the begin statement in awk?

All i am doing here is piping the output through an ls -ltr command and checking for all files from todays date in a directory with awk.
Sure there is a way to do it in bash - but I am trying to figure out how to do it in awk.


Code:

#!/usr/bin/awk -f
BEGIN {
        FS=" ";
        mydate=`/bin/date +%Y-%m-%d`
        }
{ if ($6 ~ /mydate/) {
        print $6 , $8
        sleep 1;

        }
}


ChrisCPearson 10-18-2011 11:43 PM

In AWK, to pipe the output of a command into a variable:
command | getline [var]
Here's your complete program:

Code:

#!/usr/bin/awk -f
BEGIN {
    "date +%Y-%m-%d" | getline today
}
$6 == today {
    print $6, $8
}


Tinkster 10-18-2011 11:59 PM

Quote:

Originally Posted by casperdaghost (Post 4502000)
Is there a way that I can interpolate variable in the begin statement in awk?

All i am doing here is piping the output through an ls -ltr command and checking for all files from todays date in a directory with awk.
Sure there is a way to do it in bash - but I am trying to figure out how to do it in awk.


Code:

#!/usr/bin/awk -f
BEGIN {
        FS=" ";
        mydate=`/bin/date +%Y-%m-%d`
        }
{ if ($6 ~ /mydate/) {
        print $6 , $8
        sleep 1;

        }
}


Just a word of warning: if you have filenames w/ spaces in them
your awk output for $8 won't be quite what you expected.



Cheers,
Tink

Tinkster 10-19-2011 12:00 AM

Quote:

Originally Posted by ChrisCPearson (Post 4502034)
In AWK, to pipe the output of a command into a variable:
command | getline [var]
Here's your complete program:

Code:

#!/usr/bin/awk -f
BEGIN {
    "date +%Y-%m-%d" | getline today
}
$6 == today {
    print $6, $8
}



Hi, welcome to LQ,

And nice first post. ;}



Cheers,
Tink

grail 10-19-2011 02:31 AM

As per Tink's warning, you may have even been given this link before as why you should avoid
parsing ls.

casperdaghost 10-19-2011 07:57 AM

Hey - great work guys.


All times are GMT -5. The time now is 07:23 PM.