Linux how to remove characters between square brackets of file names.

rupeshforu3

Disciple
Hi I am Rupesh from India and I have Fedora 36 Linux and some files which consists of files with names consisting of square brackets and some text in between. I want to remove these square brackets including text.

Recently I have downloaded youtube videos using yt-dlp which is youtube downloader in Linux and succeeded but its file name has the following form.

This is youtube video [abcdefg-].mp4

Here in the above file name "This is youtube video" is the title of YouTube video and abcdefg- is the id for that youtube video. mp4 is the video file extension.

Now I want to remove characters between square brackets including square brackets ie., [abcdefg-]. Here before square brackets space character is present and I want to remove it also.

Finally I want file with name as "This is youtube video.mp4".

I have 100s of files as above.

I have searched web and found some sed commands but failed.Please try to suggest how to remove characters between brackets including square brackets from file name.

Regards,
Rupesh.
 
The problem has been solved in Linux itself without any other software.

The code is

Code:
for x in *.mp4; do mv "$x" "${x// \[*\]/}"; done

Does this code works same for all situations I mean in the same way ie., just removing characters between square brackets and nothing else like deleting other characters in file name etc.,.
 
Hi I think that the code provided is the most feasible solution to the current issue but is there any way to redirect the names of files which conflicts.

Suppose there are two files with names

"This is youtube video [abcdefg-]"
"This is youtube video [abcdefh-]"

The code removes the characters present between square brackets and square brackets but here there are file conflicts.

If is there any way to redirect the names of such conflicts to another text file conflicts.txt in current directory.
 
Same thing, but before rename operation you need to extract the value of ${x// \[*\]/} to a variable like NEW_NAME and do

Bash:
find . -name $NEW_NAME

If you get results then that means you have a duplicate. If so then just append an underscore and number to it. You can keep count in another variable if reoccurrences are too many.
 
Try installing the "rename" tool and read its documentation. A while back I had used it and IIRC it has option to resolve conflicts in same filenames.
 
Back
Top