Search code examples
linuxbashcp

how to change files name under linux - regular expression


I created wrong names for log files. Example name have structure: YYYY-MM-DD_HH:MM:SS-main-DEBUG.log

Last time I had tried to copy files from dir to usb with cp command and i got exception. I googled and i found that cp does not like special signlike ":". Similar problem I found there cp: cannot create regular file: Invalid argument

How to change names (remove :) from:

2023-06-09_22:24:01-main-DEBUG.log

to:

2023-06-09_222401-main-DEBUG.log

I have a lot of logs files and i thing bash script with regular expression will be the best. Something like there:Rename multiple files in Linux following pattern

I copied solution from link above with changes here:

#! /bin/bash
for file in *[^.]log ; do
    prefix=${??????} <--what here?
    mv "$file" "$prefix".log
done

Regular expression should remove ":" from file name. How should looks regular expression for prefix variable? I can not build it. Regex is out of my mind. Please help.


Solution

  • Try

    for name in *:*.log; do
        newname=${name//:/-}
        echo mv -v -n -- "$name" "$newname"
    done