regex help

Linux for blind general discussion blinux-list at redhat.com
Wed Feb 9 17:51:12 UTC 2022


Tim here, replying inline.

> rename.ul "." " " *.txt
> repeat until all periods are gone.

Because this wil turn "dave.txt" into "davetxt", removing the period
before the extension (I see your process puts them back in after the
fact), I'd solve this with the Perl "rename" utility using

  's/(?<=\b[[:alpha:]])\.(?=.*\.[^.]*$)//g'

This requires that there be at least one period (the one before
the extension) after any period that is removed.

> rename.ul "  " " " *txt
> repeat until double spaces are gone.

Similarly, you can consolidate all sequences of spaces in one pass:

  's/  +/ /g'

Additionally, these can be combined with a semicolon in the same pass:

  rename -n 's/(?<=\b[[:alpha:]])\.(?=.*\.[^.]*$)//g;s/  +/ /g'

I have one huge ugly command that cleans up the podcast filenames in
my queue, removing troublesome characters (a "#" character in the
filename trips up my player, and I don't like periods & spaces,
swapping them to underscores and then condensing multiple runs of
them down to a single underscore).  Once you've gotten the command
figured out, I put it in a shell-script and don't have to ever think
about it again. (smile)

> So while we're on the subject of renaming stuff, can anyone suggest
> a more current rename utility where doing a simple search and
> replace on all files in the working directory is as simple as:
> 
> command "string to replace" "string to replace with" *

While not exactly what you're asking, for individual files, I often
use shell brace-expansion like

  mv long_file_{previous_bit,new_portion}_example.txt

which can save a lot of typing.  This also works nicely for taking
backups of a file like

  cp important_file.txt{,.bak}

Hope this gives you some more options to work with (and if you have
regex questions, I'm a sucker for playing with them, often hanging
out in /r/regex on Reddit helping folks there)

-tim




More information about the Blinux-list mailing list