Reputation: 107
I need to extract the value before the last underscore in shell script.
Example:
Input: first_second_third_mmddyyy.csv
Output: first_second_third
Input: first_second_mmddyy.csv
Output: first_second
Upvotes: 1
Views: 2933
Reputation: 246807
You can just use shell parameter expansion:
while read -r line; do echo "${line%_*}"; done < file
# ...........................^^^^^^^^^^
Upvotes: 1
Reputation: 4112
You can also use awk or cut as below;
awk -F '_' 'NF{NF-=1};1' file
echo "first_second_third_mmddyyy.csv" | rev | cut -d '_' -f2- | rev
Eg;
$ echo "first_second_third_mmddyyy.csv" | awk -F '_' 'NF{NF-=1};1'
first second third
NF is a variable containing the number of fields in a line.
NF-=1 is subtracting one from the NF variable, to remove last field
Upvotes: 0
Reputation: 14949
You can use this sed
:
sed 's/_[^_]*$//g' file
Test:
$ echo "first_second_third_mmddyyy.csv" | sed 's/_[^_]*$//g'
first_second_third
$ echo "first_second_mmddyy.csv" | sed 's/_[^_]*$//g'
first_second
Upvotes: 5