I have a number of directories like these :


They contain unfortunately only one file but the name is the same.


I would like to move all these files after having renamed them like this :


So, it seems like some sh scripts I see there but I can't figure out how I can take a part of the directory's name characters to form the future name of the file.

lab-results.n9999 : max number available, will not change
tests.n9999 : max number

I also may have others directories but always followed by a bunch of numbers within their names :


Any tips or help very much appreciated. I use bash 4.3.11(1) on a linux distrib.

2 Answers 2

 for F in */* ; do echo mv "$F" "${F/.2017*/.pdf}" ; done

or as a script:

#! /bin/bash
for F in */*
    echo mv "$F" "${F/.2017*/.pdf}"

It just show what to it will do. If it is what you want then remove echo and run it.

The trick is with ${F/.2017*/.pdf}. It searches for .2017* in the filename+path and replace it with .pdf.

  • Thanks for your proposal. I tested both (terminal and sh script). Filenames are unchanged as a result.. I checked each directory, the unique file is still here and its name is not the one issued from its directory.
    – Fanny Mae
    Commented May 3, 2017 at 12:26
  • @FannyMae you need to remove the echo for it to work. Hschou used the echo just so you can see what command will be run and make sure it works as expected. If it does, delete the echo and run it again and the files will be renamed. Please remember to accept this answer if it does work.
    – terdon
    Commented May 3, 2017 at 12:28
  • Hell :-( Sorry for my mistake. I just dont read twice as I should have. It works like a charm. Thanks a lot.
    – Fanny Mae
    Commented May 3, 2017 at 12:38
rename 's|^(\./[^.]*\.[^.]*).*|$1.pdf|' ./*.*.*/*.pdf

  • We select directories that have atleast 2 dots and comprise pdf files.
  • Then we keep info until the first 2 dots and construct the new filename.
  • This assumes your rename is perl-rename. Debian-based systems have perl-rename as rename, others may have it as perl-rename or prename instead.
  • Tested and working. Thanks a lot. Indeed, man rename gave me help from Perl Programmers Reference Guide.
    – Fanny Mae
    Commented May 3, 2017 at 12:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .