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
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.