justaguy
justaguy

Reputation: 3022

remove characters from filename in bash

I am trying to remove specific characters from a file in bash but am not getting the desired result.

bash

for file in /home/cmccabe/Desktop/NGS/API/test/*.vcf.gz; do
mv -- "$file" "${file%%/*_variants_}.vcf.gz"
done

file name

TSVC_variants_IonXpress_004.vcf.gz

desired resuult

IonXpress_004.vcf.gz

current result (extention in filename repeats)

TSVC_variants_IonXpress_004.vcf.gz.vcf.gz

I have tried to move the * to the end and to use /_variants_/ and the same results. Thank you :).

Upvotes: 0

Views: 125

Answers (3)

Jason Swartz
Jason Swartz

Reputation: 9

Simple way of doing this for a single file or if other files are named TSVC_variants_* in the same directory as the script or terminal.

Here is a simple one liner that will remove the TSVC_variants_* from all files with that listed in the front of the name.

rename 's/TSVC_variants_//;' *

output: IonXpress_004.vcf.gz

Upvotes: 1

sjsam
sjsam

Reputation: 21955

 find . -type f -name "*.vcf.gz" -exec bash -c 'var="$1";mv $var ${var/TSVC_variants_/}' _ {} \;

may do the job for you .

Upvotes: 1

tripleee
tripleee

Reputation: 189317

${var%%*foo} removes a string ending with foo from the end of the value of var. If there isn't a suffix which matches, nothing is removed. I'm guessing you want ${var##*foo} to trim from the beginning, up through foo. You'll have to add the directory path back separately if you remove it, of course.

mv -- "$file" "/home/cmccabe/Desktop/NGS/API/test/${file##*_variants_}"

Upvotes: 4

Related Questions