String split

Split string of variable ${FILE} by delimiter '_'

# filename example

FILE=SRR01234_mapped_ecoli.txt

echo ${FILE%%_*} # get all before first delimiter '_'

SRR01234

echo ${FILE%_*} # get all before last delimiter '_'

SRR01234_mapped

echo ${FILE##*_} # get all after last delimiter '_'

ecoli.txt

echo ${FILE#*_} # get all after first delimiter '_'

mapped_ecoli.txt

Basename examples

# get filename without path prefix

F=/path/to/sample/SRR01234_mapped_ecoli.txt

FILE=`basename ${F}`

echo ${FILE}

SRR01234_mapped_ecoli.txt

# get filename without path prefix and without extension

F=/path/to/sample/SRR01234_mapped_ecoli.txt

FILENAME=`basename ${F%%.*}` # get all before first '.' (remove file ending)

echo ${FILENAME}

SRR01234_mapped_ecoli

# get sample-ID

F=/path/to/sample/SRR01234_mapped_ecoli.txt

SAMPLE=`basename ${F%%_*}` # get all before '_'

echo ${SAMPLE}

SRR01234

# get speciesname "ecoli"

F=/path/to/sample/SRR01234_mapped_ecoli.txt

FILENAME=`basename ${F%%.*}` # get all before first '.' (remove file ending)

SPECIES=${FILENAME##*_} # get all after last delimiter '_'

echo ${SPECIES}

ecoli

Alternative use: cut

# get first word (-f 1) based on delimiter '_'

FILE=SRR01234_mapped_ecoli.txt

SAMPLE=$( cut -d '_' -f 1 - <<< "${FILE}" )

echo ${SAMPLE}

SRR01234