Search code examples
linuxbashshelldateglob

How replace string with regex in bash script?


I have this working in terminal (it just remove the date using string replacement)

NAME="/home/me/a_path/2023-04-10 filename"
NEW_NAME=$(echo ${NAME//20[0-9][0-9]-[0-9][0-9]-[0-9][0-9] /})
echo ${NEW_NAME}
>>> Expected output :  "/home/me/a_path/filename"

But this is not working (it output the non-modified string) in script, I can't understand why.

I tried different quotation marks positions and some other things that I found on SO, but nothing has worked for me yet. I tried using sed it does not work better.

Edit: The example I gave is working, so probably a typo in my full script


Solution

  • Here is another approach without regex based on the inputs provided in the asked question.

    #!/bin/bash
    
    NAME="/home/me/a_path/2023-04-10 filename"
    DIR=$(dirname "${NAME}")
    FILE=$(basename "${NAME}" | awk '{print $NF}')
    
    echo "${DIR}/${FILE}"
    
    

    The output:
    /home/me/a_path/filename