I would like to run a .sh script to rename a file which is in the directory desktop/reports/don of my computer. An example of what I need is to rename:
TACOS_2013-Jan-22__00-50-00_UTC.csv
to
TACOS_20130122_005000.csv
I have the following script which was created using windows batch script(.bat file). I would like to convert this into linux shell script.
@echo off
setlocal
for /f "tokens=2-7 delims=_.-" %%A in ('dir /B TACOS_*') do (
setlocal enabledelayedexpansion
call :getmonth %%B
ren TACOS*_*%%A-%%B-%%C*_*%%D-%%E-%%F_UTC.csv TACOS_%%A!mon!%%C_%%D%%E%%F.csv
endlocal
)
:getmonth
if "%1" equ "Jan" set mon=01
if "%1" equ "Feb" set mon=02
if "%1" equ "Mar" set mon=03
if "%1" equ "Apr" set mon=04
if "%1" equ "May" set mon=05
if "%1" equ "Jun" set mon=06
if "%1" equ "Jul" set mon=07
if "%1" equ "Aug" set mon=08
if "%1" equ "Sep" set mon=09
if "%1" equ "Oct" set mon=10
if "%1" equ "Nov" set mon=11
if "%1" equ "Dec" set mon=12
goto :eof
endlocal
this is what i have done so far..Please help
#!/bin/bash
month["Jan"]=01
month["Feb"]=02
month["Mar"]=03
month["Apr"]=04
month["May"]=05
month["Jun"]=06
month["Jul"]=07
month["Aug"]=08
month["Sep"]=09
month["Oct"]=10
month["Nov"]=11
month["Dec"]=12
directory="desktop/reports/Don/"
for path in "${directory}TACOS_"*; do
path=${path#${directory}}
newpath=${path:0:10}${month[${path:11:3}]}${path:15:2}
newpath=${newpath}__$(tr -d '-' <<< ${path:19:8}).csv
echo "${directory}${path}" "${directory}${newpath}" # Run this one first!!!
# mv "YOUR/PATH/${path}" "YOUR/PATH/${newpath}"
done
Now that you made it a bit clearer, I guess this is what you want:
The solution in a bash script:
This converts the string
path=TACOS_2013-Jan-22__00-50-00_UTC.csvintonewpath=TACOS_20130122__005000.csv, and renames the initial filemv‘ing it to the new path constructed.As in explanation,
bashoffers you associative arrays, that you have to declare prior to any operation usingdeclare -A assoc_array.In
bashyou can take string intervals, setting anoffset, alength, and doing${string:offset:length}. Concatenation is performed by juxtaposition of strings, and assignments must have no spaces betweenleft_value=right_value.In addition, you have
trcommand, translating your string frominitialtoinitial_without_characters, since the flag-dhas been used. You may take a look atman trfor further reference.Edit:
Since you don’t have a more recent version of
bash, you can use the following code: