Regular expression in rename Unix command

Viewed 105

I am trying to rename some files and am pretty new to regular expressions. I know how to do this the long way, but I am trying some code golf to shorten it up.

My file:

abc4800_12_S200_R1_001.fastq.gz

My goal:

abc4800_12_R1.fastq.gz

Right now I have a two-step process for renaming it:

rename 's/_S[0-9]+//g' *gz
rename 's/_001//g' *gz

But I was trying to shorten this into one single line to clean it up in one go.

I was trying to use a regular expression to skip over the parts in between, but I don’t know if that is actually a possibility in this function.

rename 's/_S[0-9]+_*?_001//g' *gz
3 Answers

Use a capture group to preserve the middle part of the segment you're replacing.

rename 's/_S\d+_(.*)_001/_$1/' *gz

With your shown samples, please try the following rename command. I am using the -n option here which is a dry run for command. Once you are happy with the output (like how files are going to rename if we run actual code), remove the -n option from the following rename code.

rename -n 's/(^[^_]*_[^_]*)_[^_]*(_[^_]*)[^.]*(\..*$)/$1$2$3/' *.gz

The output will be as follows:

rename(abc4800_12_S200_R1_001.fastq.gz, abc4800_12_R1.fastq.gz)

Explanation:

(^[^_]*_[^_]*)  ## Creating the 1st capturing group which captures everything from starting to just before 2nd occurrence of _ here.
_[^_]*          ## Matching (without a capturing group) _ then just before the next occurrence of _ here.
(_[^_]*)        ## Creating the 2nd capturing group here which matches _, followed by before the next occurrence of _ here.
[^.]*           ## Matching everything just before dot comes (not capturing here).
(\..*$)         ## Creating the 3rd capturing group which has a dot till the end of line in it.

You are trying to replace two parts in the string with nothing. Use the alternation operator. It will match the left or the right side; replacing any match with the same replacement string (i.e. nothing):

rename 's/_S[0-9]+|_001//g' *gz
Related