$ ls
about-bar   about-bar.pdf   about-foo   about-fou.pdf
$ for f in *about-*.pdf; do mv "$f" "$(echo $f | sed -E 's:(about-.*).pdf:\1:')";done
$ find .

What would be an efficient way to skip files that don't have a corresponding directory? In this case, only about-bar.pdf would be moved, and about-fou.pdf wouldn't be renamed (specifically, .pdf stripped).

Thank you.


No sed needed here; we can use standard bash expression of ${file%.pdf} to strip off the .pdf extension

$ ls
about-bar/  about-bar.pdf  about-foo/  about-fou.pdf

$ for a in *.pdf
> do
>   dir=${a%.pdf}
>   if [ -d "$dir" ]
>   then
>     mv -i "$a" "$dir"
>   fi
> done

$ ls
about-bar/  about-foo/  about-fou.pdf

$ ls *


  • It seems that you are suggesting a script, whereas I was trying to do it in one line. I expect the modified code to return: – Erwann Jul 15 '16 at 2:13
  • 2
    That was a single command line, just typed in over multiple lines for readability. You can reformat it with ; in the right place. i.e. for a in *.pdf; do dir=${a%.pdf}; if [ -d "$dir" ]; then mv -i "$a" "$dir"; fi; done – Stephen Harris Jul 15 '16 at 2:15
  • Yes, this solves my problem. Would it be possible to use sed with the following change: do dir=$(echo $f | sed ... )? (which may accommodate more complex patterns than the one suggested by my example) – Erwann Jul 15 '16 at 3:02
  • Right, and sometimes calling out to an external program like sed is the easiest way of doing it. But it's not as efficient (especially for large directories), so I recommend avoiding it for the simple cases like this one. – Stephen Harris Jul 15 '16 at 3:05
  • Here's a version I just tested that accommodates a prefix before about: $ ls about-bar about-fou.pdf about-foo bazabout-bar.pdf $ for f in *about-*.pdf; do dir="$(echo $f | sed -E 's:.*(about-.*).pdf:\1:')";echo $dir; done about-bar – Erwann Jul 15 '16 at 3:15

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.