Awk/sed part of filename

awkcommand linefilenamessed

I want to awk/sed only prefix of name of files, whenever I put a filename as a parameter to my command line.

For example,

I have multiple files:

a.fastq.gz
b.fastq.gz
c.fastq.gz
d.fastq.gz

If I execute:

sh test.sh --INFILE b.fastq.gz

My desired output would be:

b

Something I tried and failed was,

prefix="sed 's/.fastq//' ${INFILE}"

Best Answer

Using shell parameter expansion (assuming you are assigning your filename to INFILE):

INFILE=b.fastq.gz
prefix=${INFILE%%.*}

Or if your suffix is sure to be fixed and you want to be more precise (always recommended when possible):

prefix=${INFILE%.fastq.gz}

${parameter%word}

${parameter%%word}

The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the ‘%’ case) or the longest matching pattern (the ‘%%’ case) deleted. If parameter is ‘@’ or ‘’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

Related Question