3

I have a number of directories like these :

./lab-results.n3668.2017-01-16
./lab-results.n471.2017-02-24
./tests.n287.2017-01-28
./tests.n4501.2017-03-04

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

./lab-results.n3668.2017-01-16/lab-results.pdf
./lab-results.n471.2017-02-24/lab-results.pdf
./tests.n287.2017-01-28/tests.pdf
./tests.n4501.2017-03-04/tests.pdf

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

./lab-results.n3668.pdf
./lab-results.n471.pdf
./tests.n287.pdf
./tests.n4501.pdf

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 :

./xxxxxxx.n9999
./yyyyyy.n9999
./zzz.n9999

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

2 Answers 2

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

or as a script:

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

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.

3
  • 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
    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
    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
    May 3, 2017 at 12:38
1
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.
1
  • Tested and working. Thanks a lot. Indeed, man rename gave me help from Perl Programmers Reference Guide.
    – Fanny Mae
    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 .