1

I have a series of files in a folder with a string in the middle of the filenames starting with _S (_S1, S2, S143 ....), which I need to get rid of/replace with just and underscore. Like this

file1_S1_R1 
file2_S2_R1 
file3_S95_R1
file4_S143_R1

which should be

file1_R1 
file2_R1 
file3_R1
file4_R1

I have tried the standard

rename 's/_S*_/_/g' *

command. However, nothing happens. Apparently, the wildcard does not work with rename on my computer. Escaping the _ with backslash (_ is not a reserved character anyway) or such tricks makes no difference. What am I doing wrong?

2

Assuming that your rename utility is the Perl rename utility (which takes a Perl expression, typically a substitution expression, as its 1st argument):

$ ls -l
total 0
-rw-r--r--  1 kk  wheel  0 Oct  4 11:00 file1_S1_R1
-rw-r--r--  1 kk  wheel  0 Oct  4 11:00 file2_S2_R1
-rw-r--r--  1 kk  wheel  0 Oct  4 11:00 file3_S95_R1
-rw-r--r--  1 kk  wheel  0 Oct  4 11:00 file4_S143_R1
$ rename 's/_S\d*_/_/g' *
$ ls -l
total 0
-rw-r--r--  1 kk  wheel  0 Oct  4 11:00 file1_R1
-rw-r--r--  1 kk  wheel  0 Oct  4 11:00 file2_R1
-rw-r--r--  1 kk  wheel  0 Oct  4 11:00 file3_R1
-rw-r--r--  1 kk  wheel  0 Oct  4 11:00 file4_R1

You got the regular expression wrong by possibly assuming that you would use a filename globbing pattern and not a Perl regular expression. I fixed it by changing S* (matches zero or more S characters) to S\d* (matches an S followed by zero or more digits).

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.