0

I need to rename some files using a loop but I can't get it to work as I am still very new at Linux. the files that need to be renamed are:

E9-GOWN33_multiplemap.bin.10.fa  
E9-GOWN33_multiplemap.bin.16.fa  
E9-GOWN33_multiplemap.bin.21.fa  
E9-GOWN33_multiplemap.bin.7.fa

to a shorter name such as:

E9.bin.10.fa
E9.bin.16.fa
E9.bin.21.fa
E9.bin.7.fa

I have used rename and mv and other loops I've seen in threads but still cannot get it to work. any input is much appreciated! thank you!

2
  • 1
    why do you need to use a loop? ... also, please add your attemped code to your post – jsotola Apr 16 '20 at 16:57
  • I have over 78 samples in one of my directories that need to be renamed, but I have got it! using the following: for file in *.fa; do E23="${file/-GOWN186_multiplemap/}"; mv -- "$file" "$E23"; done – megan Apr 16 '20 at 17:32
2

If you have perl rename (default on Ubuntu, Debian and many other systems), you can just do

rename -n 's/-GOWN33_multiplemap//' *fa

If that gives you the right file names, run without the -n to actually rename them:

rename 's/-GOWN33_multiplemap//' *fa
2

You can try this:

for f in *.fa; do 
  echo mv "$f" "${f%-*}.${f#*.}"
done

Result:

E9.bin.10.fa
E9.bin.16.fa
E9.bin.21.fa
E9.bin.7.fa
0

Assuming that all those files are in the current directory, and that all of them, and no other files, match the globbing pattern

E9-GOWN33_multiplemap.bin.*.fa

Then, you may loop over these with

for name in E9-GOWN33_multiplemap.bin.*.fa; do
   # more code here
done

Inside the loop, $name will be the name of one of these files.

Given the name E9-GOWN33_multiplemap.bin.10.fa in $name, we can remove the E9-GOWN33_multiplemap bit from the start of the name with

${name#E9-GOWN33_multiplemap}

It's then just a matter to re-attach the initial E9 string to the front of that to create E9.bin.10.fa:

newname=E9${name#E9-GOWN33_multiplemap}

With mv we may then rename the old filename to the new:

mv "$name" "$newname"

So, with that we have

for name in E9-GOWN33_multiplemap.bin.*.fa; do
    newname=E9${name#E9-GOWN33_multiplemap}
    mv "$name" "$newname"
done

or shorter,

for name in E9-GOWN33_multiplemap.bin.*.fa; do
    mv "$name" "E9${name#E9-GOWN33_multiplemap}"
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.