David Z
David Z

Reputation: 7041

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

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

Answers (4)

L&#233;a Gris
L&#233;a Gris

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

alparslan
alparslan

Reputation: 173

$ tr "_" " " <<< "a_b_c_d"

a b c d

Upvotes: 0

LinconFive
LinconFive

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

Nic3500
Nic3500

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

Related Questions