0

We regularly have images that are named 1234567890_GH_ANI_EPS.eps with variables after the first underscore. I would like to write a bash script to remove the first underscore up to the file extension.

Original file name: 1234567890_GH_ANI_EPS.eps New File Name: 1234567890.eps

I was able to achieve removing the last _EPS by using the below code:

for f in "$@"
do
     mv "$f" "${f%_*}.eps"
done

And have tried the below and the file disappears:

for f in "$@"
do
     mv "$f" "${f%%_*}.eps"
done

any help would be appreciated. Thank you

djoins
  • 15
  • 3
  • Use `${f%%_*}.eps` to match from the _first_ underscore instead of the last one. – Charles Duffy Mar 26 '21 at 18:22
  • ...you say you tried that, you don't say why/how it didn't work. Without details on why it didn't work, how are we supposed to answer the question? – Charles Duffy Mar 26 '21 at 18:22
  • My apologies, when using ```${f%%_*}.eps``` the file dissapears, and am not sure what is happening to it. – djoins Mar 26 '21 at 18:27
  • `a="1234567890_GH_ANI_EPS.eps"` => `echo $(echo $a | cut -f1 -d"_").$(echo $a | cut -f2 -d".") ` – Ivan Mar 26 '21 at 18:34
  • 1
    @Ivan, that's very inefficient. `$()` runs a subshell; `cut` is implemented by a whole new executable. And `echo $a` (as opposed to `echo "$a"`) [has its own bugs](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else). – Charles Duffy Mar 26 '21 at 18:41
  • @djoins, run `bash -x yourscript` to get logs of what the actual `mv` commands it runs are. (You could also put `set -x` in the script to turn on tracing, and `set +x` later to turn it off). – Charles Duffy Mar 26 '21 at 18:42
  • @Charles Duffy, not sure what it was, but i restarted my machine and ```mv "$f" "${f%%_*}.eps"``` is working as intended. Thanks for your help – djoins Mar 26 '21 at 19:15

0 Answers0