Reputation: 7041
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
Upvotes: 7
Views: 21952
Reputation: 19545
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"
Upvotes: 18
Reputation: 2012
IFS
is the bash way delimiter, we can cut string as below:
IFS='_' read -r -a array <<< "a_b_c_d"
echo "${array[0]}"
Upvotes: 3
Reputation: 8591
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.
Upvotes: 3