kelvinfrog kelvinfrog - 5 months ago 10
Linux Question

rename file names using folder name but keep the digit same

I want to rename my files in the subdirectories using the folder name. My files are like this format

fastqjoin
un1
fasta
fastq
un2
fasta
fastq


and I want to change it to

foldername
un1
fasta
fastq
un2
fasta
fastq


I found this script can change the filename using the folder name but I want to add the regular expression so that it can change all files in one script

for subdir in *; do mv $subdir/fastqjoin.un1.fasta $subdir/$subdir.un1.fasta; done;


I have tried replacing the script with
un[0-9].fast/D, un/d.fast/D
but none of them work. For example:

f`or subdir in *; do mv $subdir/fastqjoin.un[0-9].fast/D $subdir/$subdir.un[0-9].fast/D; done;`

Answer

Use ${variable#fastqjoin} to remove fastqjoin from the beginning of the variable, and another loop to iterate over the files:

for subdir in *; do
    for pth in $subdir/*; do
        file=`basename $pth`;
        mv $pth $subdir/$subdir${file#fastqjoin};
    done;
done
Comments