How to split a string by underscore and extract an element as a variable in bash?

Viewed 6037

Suppose I have a string such like s=DNA128533_mutect2_filtered.vcf.gz. How could I extract the DNA128533 as an ID variable.

I tried

id=(cut -d_ -f1 <<< ${s}
echo $id

It seems not working. some suggestions? Thanks

3 Answers

No need to spend a sub-shell calling cut -d'_' -f1 and using bashism <<< "$s".

The POSIX shell grammar has built-in provision for stripping-out the trailing elements with variable expansion, without forking a costly sub-shell or using non-standard Bash specific <<<"here string".

#!/usr/bin/env sh

s=DNA128533_mutect2_filtered.vcf.gz
id=${s%%_*}
echo "$id"

You want to filter the DNA... part out of the filename. Therefore:

s="DNA128533_mutect2_filtered.vcf.gz"

id=$(echo "$s" | cut -d'_' -f1)
echo "$id"

If you want to use your way of doing it (with <<<), do this:

id=$(cut -d'_' -f1 <<< "$s")
echo "$id"

Your command has some syntax issues, like you are missing ). And you want the output of the command to be stored in variable id, so you have to make it run via the $( ) syntax.

IFS is the bash way delimiter, we can cut string as below:

IFS='_' read -r -a array <<< "a_b_c_d"
echo "${array[0]}"
Related