I have a variable set with var='type_cardio_10-11-2017'
. I need to remove the last 10 letters from the variable, and append the remaining value to var2
.
I tried with the following script, but it doesn't work as expected.
var=type_cardio_10-11-2017
var2=${var} | cut -f1 -d "_"
echo ${var2}
The output I want is type_cardio.
To remove everything from after the last _
in var
and assign the result to var2
:
var2=${var%_*}
The parameter expansion ${parameter%word}
removes the pattern word
(_*
in this case) from the end of the value of the given variable.
The POSIX standard calls this a "Remove Smallest Suffix Pattern" parameter expansion.
To remove the last underscore and the 10 characters after it, use
var2=${var%_??????????}
To remove characters corresponding to a date string such as the one in your example, use
var2=${var%_[0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]}
Which pattern you use depends on how carefully you want to perform the match.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments