简体   繁体   中英

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 ie 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM