-1

I'd like to combine two parts of code into a script that can me used to batch rename files. So far, I got this far:

file name before: 12345-[name]_ABC_12345.txt

file name after: name

for f in *.txt;  do 
    mv "$f" "${f//]*}";
done

for f in *txt;  do 
    echo mv "$f" "${f/*[/}";
done
user2904120
  • 416
  • 1
  • 4
  • 18
  • What exactly is your question? What should happen if there are files which match the second wildcard, but not the first? Any particular reason you are not simply doing both steps inside the first loop? – tripleee May 30 '16 at 10:27

1 Answers1

1

Assuming I understand your requirement correctly, you seem to be looking for

for f in *\[*\]*.txt; do
    head=${f%%\]*}
    mv "$f" "${head#*\[}"
done

This will extract the part between the first pair of square brackets and use that as the destination name. ${var#head} and ${var%tail} return the value of $var with any prefix matching the glob expression head, or any suffix matching tail, respectively, trimmed off. The double-operator variants trim the longest instead of the shortest match.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • and how to add '.txt' at the end of the new name? – user2904120 May 30 '16 at 11:22
  • 1
    `mv "$f" "${head#\*[}.txt"` but really, this should not be hard to figure out; and, if that's what you really want, why didn't you put this requirement in the question to begin with? – tripleee May 30 '16 at 11:47