0

I have 3 files in one directory like below:

file_str_23.txt  
file_jan_24.txt  
file_feb_25.txt  

Here I would like to replace the first file name 'file_str' with 'file_', so finally the file name should be 'file_23.txt'.

The problem is that I don't know the exact number in the file name, so I should go with 'file_str' string only.

How to do this?

3 Answers 3

3

To change single file's name, use mv:

mv file_str_23.txt file_23.txt

And if you want to do this in batch, you could try rename, which accepts regular expression:

rename 's/_.*?_/_/' file_*

First argument is a Perl regex substitution expression. It's general form is:

s/WHAT_TO_LOOK_FOR/WHAT_TO_PUT_INSTEAD/

In our case WHAT_TO_LOOK_FOR is _.*?_ and WHAT_TO_PUT_INSTEAD is _.

Now, _.*?_ means: "Match underscore followed by any number of any characters (.*?), followed by another underscore". For instance, in string "file_str_23.txt" it will match "str".

This matched part of the file name will be replaced with _ (our WHAT_TO_PUT_INSTEAD part).

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

3 Comments

Hmmm Here the problem is I dont know the exact number in the file name, so i should go with 'file_str' string only.
Okay, see updated answer. Your orignal question didn't mention batch rename ;p
Can you please explain 's/_.*?_/_/' part?
1

if you're using bash, you could also use this

for F in file_*.txt ; do 
    mv ${F} file_${F#file_*_}
done

Which is super easy to make into a one-liner:

for F in file_*.txt ; do mv ${F} file_${F#file_*_} ; done

Comments

1

You can try this for loop that should work without any external utility:

for f in *_*_*.txt; do
    mv "$f" "${f/_*_/_}"
done

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.