In a directory, I have about 150 files with a certain extension, for example:


Now I want to copy all of these files also to a new filename (without extension):


What is the shortest way to get this done? Is it possible without writing a loop in a bash file?

Edit: Thank you for your answers (dirkt, John Newman).
After seeing the answers I'll stick with the shorter one, although it has a loop.

  • With zsh: autoload zmv; zmv -C -n '(*).ext' '$1' (remove the -n if you like what you see...) – don_crissti Dec 19 '16 at 20:43

It's possible without writing a script ("bash file"), but not without using a loop:

for f in *.ext ; do cp -- "$f" "$(basename "$f" .ext)" ; done

basename can be used to remove the suffix.

| improve this answer | |
  • Be sure to quote your variables, lest one of those names have, say, a space in them – Eric Renouf Dec 19 '16 at 18:39

It's definitely possible without a loop. Is it good ... I'll leave that up to you.

$ find . -type f -name "*.ext" -print0 | xargs -0 -I {} echo cp -T {} {}SUB | sed -e 's/\.extSUB//g'

append a pipe to sh to get out of dry run mode. Backticks are no good as it strips the newlines, unless you deal with $IFS. And there are other character issues with backticks as mentioned. Also need the cp -T as the last argument is normally expecting a directory.

I don't have enough "rep" to comment on the above, but you can use various tricks with bash ${} to avoid the fork of basename.

Substring: ${f:0:-4} or longest match: ${f%%.ext}

| improve this answer | |
  • Without the echo, what would be getting piped to sed? Also, without the echo wouldn't the cp happen before you strip the extra text from the end? – Eric Renouf Dec 19 '16 at 18:07
  • you're correct .. i obviously never bothered to try that. i edited it. – John Newman Dec 19 '16 at 18:25
  • Although using backticks (or $()) will rebreak things if there are unsafe characters in the filenames, which you were protecting against with -print0 – Eric Renouf Dec 19 '16 at 18:38
  • edited again AND actually fully tested it this time. harder than I thought. backticks strip the new lines. – John Newman Dec 19 '16 at 18:47
  • Sadly, this still fails for my file with a space.ext and also $'new\nline.ext' – Eric Renouf Dec 19 '16 at 18:54

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.