1

Suppose I have files named: 93162-117352 - May 24, 2017 345 PM_16_163_student.csv

I want to rename it to be: 16_163_student.csv

How do I do this with rename?

ilkkachu
  • 138,973
orrkid
  • 11
  • 1
  • 2
  • So you know that rename is the tool of your choice and from man rename you probably know that you have to use perl-style s/pattern/replace/ command for your purpose? So your actual question seems to be: How to define a pattern to match that first part of the filename, correct? And as you included the "wildcards" tag, you probably didn't understand that you need to use regular expressions instead of wildcard globbing here: rename "s/[^_]*_//' *.csv – Philippos May 26 '17 at 08:17
  • @Philippos be careful - there are two incompatible implementations of rename out there. One is the perl-based one but there's another RHEL-preferred one too. – Chris Davies May 26 '17 at 09:26
  • Or just rename 's/.*?_//' ./*.csv (some variants support a -i) – Stéphane Chazelas May 26 '17 at 11:36

1 Answers1

1

You want to remove everything in the filename up to and including the first _. This is similar, but easier, to what was asked for in "change names of files consistently"

My solution would be (assuming a POSIX shell like bash):

for name in *.csv; do
    mv -i -- "$name" "${name#*_}"
done

The ${name#*_} will remove everything up to and including the first _ in the name.

This is assuming the files you want to work on all matches the pattern *.csv.

I've added a -i so you get an option to abort if that would cause files to be lost (for instance because there's both a A_x.csv and B_x.csv).

Kusalananda
  • 333,661