1

I need to remove a serial number in my file name which is between - and _ (the underscore should also be removed).

Original file name : 20190815-12345_table_file.rar

Expected : 20190815-table_file.rar

My bash code :

for f in ./*.rar;
do fn=`echo $f|sed 's/^-[0-9].*_$/-/g'`;
mv "$f" "$fn";
done;

I tried something like this because i know that my numbers are starting with "-" (so ^) are numbers ([0-9].*) and are ending with "_" (so $) and I want to replace numbers by "-".

But with this method it doesn’t work.

2 Answers 2

2

You’re regex for sed doesn’t match the way you want: the start and end delimiters are anchors to the start and end of a line. Also, you want [0-9]* without the dots for any amount of digits.

Try this instead:

for f in ./*.rar; do
  fn="$( sed 's/-[0-9]*_/-/g' <<<"$f" )"
  mv "$f" "$fn"
done

In bash, you can use a parameter expansion to do the substitute without sed; I’ve forgotten the exact syntax, so I’ll leave it out for now and add it later. Check man bash for the details.

Sign up to request clarification or add additional context in comments.

Comments

1

An all Bash solution is:

for f in ./*.rar; do
  mv "$f" "${f/-*([0-9])_/-}"
done

You must have the extglob shell option enabled with shopt -s extglob for the *() pattern to work.

See the Bash Reference Manual or this answer for more information on how the parameter expansion works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.