Reputation: 967
I have a variable
of the format $var_YYYY_MM_DD_HH_MM_SS.txt
Eg: variable=sample_data_2017_01_01_10_22_10.txt
I need to extract the following from this variable:
Year=YYYY
Month=MM
Date=DD
Can you please help?
Upvotes: 1
Views: 1859
Reputation: 12887
Building on some of the other awk solutions a more complete solution would be:
echo $variable | awk -F_ '{ printf "Year="$3"\nMonth="$4"\nDate="$5"\n" }'
Upvotes: 0
Reputation: 14949
You can simply use read
command with setting IFS='_'
.
$ variable=sample_data_2017_01_01_10_22_10.txt
$ IFS='_' read -r tmp tmp Year Month Date tmp <<< "$variable"
$ echo "$Year : $Month : $Date"
2017 : 01 : 01
Upvotes: 1
Reputation: 4390
Using awk
Year=$(echo $variable | awk '{split($0,a,"_"); print a[3]}')
Month=$(echo $variable | awk '{split($0,a,"_"); print a[4]}')
Day=$(echo $variable | awk '{split($0,a,"_"); print a[5]}')
Upvotes: 0
Reputation: 9362
You could try:
Year=$(echo $variable | cut -d '_' -f3)
Month=$(echo $variable | cut -d '_' -f4)
Date=$(echo $variable | cut -d '_' -f5)
This only works if you are sure your variable is laid out in the exact way you describe in your question though. It splits up the string delimited by the '_' character and then returns the field denoted -f
argument to cut.
Upvotes: 1
Reputation: 85800
Use the native bash
, regex operator ~
and use the captured groups to store them in variables for using it later.
variable="sample_data_2017_01_01_10_22_10.txt"
if [[ $variable =~ ^sample_data_([[:digit:]]{4})_([[:digit:]]{2})_([[:digit:]]{2}).*$ ]]; then
year="${BASH_REMATCH[1]}"
month="${BASH_REMATCH[2]}"
date="${BASH_REMATCH[3]}"
fi
Upvotes: 4