Issue
I am using the following awk
(from my previous post - how to get list of folders that older then 30 days ) in order to print the folders that are older than XX days
as the following example. Regarding this example we set 30 days as constant in awk
syntax
awk -v d="$(date -d '-30 days' +'%F')" '$1 < d' file
2023-09-14 /user/hdfs/.sparkStaging/application_1693406696051_0046
2023-09-14 /user/hdfs/.sparkStaging/application_1693406696051_0049
2023-09-14 /user/hdfs/.sparkStaging/application_1693406696051_0051
2023-09-14 /user/hdfs/.sparkStaging/application_1693406696051_0063
2023-09-14 /user/hdfs/.sparkStaging/application_1693406696051_0064
2023-09-14 /user/hdfs/.sparkStaging/application_1693406696051_0065
2023-09-18 /user/hdfs/.sparkStaging/application_1693406696051_0107
Now we want to replace the constant 30 days
with a variable, and we changed the awk
as the following, so we want to pass the day
value to awk
, as day=100
awk -v day=100 -v d="$(date -d '-day days' +'%F')" '$1 < d' file
but we do not see the expected output, and the day
setting is not affected at all.
Could you please point out my error?
Solution
The command substitution runs before Awk runs. Also, the single quotes prevent the variable from being interpolated by the shell.
The correct code would look something like
day=100
awk -v d="$(date -d "-$day days" +'%F')" '$1 < d' file
Make sure you understand the difference between a shell variable and an Awk variable. The shell doesn't know anything about Awk, and vice versa. (Much like you don't know the names or values of variables in the code which is running your computer, unless it exposes an interface to let you inspect its current state.)
Answered By - tripleee Answer Checked By - Dawn Plyler (WPSolving Volunteer)