Steve Fitzsimons
Steve Fitzsimons

Reputation: 3904

Linux remove a single underscore before and after a character using command line

How do I remove a single underscore (_) before and after a character?. I have a large number of files named like

filename_part_one_-_filename_part_two.file

To get the filename to the above format I used rename 'y/A-Z/a-z/' * to lowercase and rename 's/ /_/g' * to strip whitespace. The final step is to remove the underscore before and after the -. Preferably using a one line command.

Upvotes: 0

Views: 671

Answers (1)

Lars Fischer
Lars Fischer

Reputation: 10129

To substitute _-_ with - use s/_-_/-/. You can put it all into one argument to rename:

touch "FileName Part one_-_filename_part_two.file"
rename 'y/A-Z/a-z/; s/ /_/g; s/_-_/-/' "FileName Part one_-_filename_part_two.file"
ls *.file
> filename_part_one-filename_part_two.file

Upvotes: 1

Related Questions