NisHanT
NisHanT

Reputation: 3

Can't input date variable in bash

I have a directory /user/reports under which many files are there, one of them is :

report.active_user.30092018.77325.csv

I need output as number after date i.e. 77325 from above file name.

I created below command to find a value from file name:

ls /user/reports | awk -F. '/report.active_user.30092018/ {print $(NF-1)}'

Now, I want current date to be passed in above command as variable and get result:

ls /user/reports | awk -F. '/report.active_user.$(date +'%d%m%Y')/ {print $(NF-1)}'

But not getting required output.

Tried bash script:

#!/usr/bin/env bash

_date=`date +%d%m%Y`

 active=$(ls /user/reports | awk -F. '/report.active_user.${_date}/ {print $(NF-1)}')


 echo $active

But still output is blank.

Please help with proper syntax.

Upvotes: 0

Views: 252

Answers (2)

glenn jackman
glenn jackman

Reputation: 246837

Don't parse ls

You don't need awk for this: you can manage with the shell's capabilities

for file in report.active_user."$(date "+%d%m%Y")"*; do
    tmp=${file%.*}      # remove the extension
    number=${tmp##*.}   # remove the prefix up to and including the last dot
    echo "$number"
done

See https://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion

Upvotes: 0

bbichero
bbichero

Reputation: 66

As @cyrus said you must use double quotes in your variable assignment because simple quote are use only for string and not for containing variables.

Bas use case

number=10
string='I m sentence with or wihtout var $number'
echo $string

Correct use case

number=10
string_with_number="I m sentence with var $number"
echo $string_with_number

You can use simple quote but not englobe all the string

number=10
string_with_number='I m sentence with var '$number
echo $string_with_number

Upvotes: 1

Related Questions