Renaming multiple files using sed or awk

时间:2015-04-27 13:16:07

标签: linux bash awk sed

I have a DVR recorder that sends files to my linux ftp server with a specific name, but I need to change to another name format so they can be used on the older software. The original files came with this format:

DVR_ch1_principal_20150427094000_20150427100000.dav

DVR=Device Name
ch1=channel#

principal=stream type

20150427094000=starting date in year,month,day,hour,minute,second format

20150427100000=end date in year,month,day,hour,minute,second format

I need to modify all files in a folder to this format:

ch1_09.04.00-10.00.00.dav

ch1=channel#

09.04.00=starting time in hh.mm.ss

10.00.00=end time in hh.mm.ss

I know it can be done using sed or ark, but it's beyond my knowledge.

Thanks in advance

2 个答案:

答案 0 :(得分:0)

sed -n '
# ch1_09.04.00-10.00.00.dav
/^DVR_ch/ {
   s/.*\(ch[0-9]\{1,\}\).*\([0-9]\{6\}\)_.*\(([0-9]\{6\}.\{4\}\)$/\1-\2-\3
   s/\([0-9][0-9]\)\([0-9][0-9]\)\([0-9][0-9]\)/\.\2.\3\
/g
   p
   }
#ch1=channel
/=channel/ p

#=starting date 
/=starting date/ s/[0-9]*\([0-9][0-9]\)\([0-9][0-9]\)\([0-9][0-9]\)=.*/\
\1.\2.\3=starting time in hh.mm.ss/p

#=end date 
/=starting date/ s/[0-9]*\([0-9][0-9]\)\([0-9][0-9]\)\([0-9][0-9]\)=.*/\
\1.\2.\3=end time in hh.mm.ss/p
' YourFile

自我评论(posix版本所以' - postix'在linux GNU sed中) 它主要是从行

重新格式化信息

答案 1 :(得分:0)

AWK& bash版本:

for FNAME in $(ls -1 *.dav)
  do
    channel=$(echo ${FNAME} | awk -F _ '{print $2}')
    starttime=$(echo ${FNAME} | awk -F _ '{print $4}')
    endtime=$(echo ${FNAME} | awk -F _ '{print $5}')
    #
    echo ${channel}
    #
    STARTH=${starttime:8:2}
    STARTM=${starttime:10:2}
    STARTS=${starttime:12:2}
    ENDH=${endtime:8:2}
    ENDM=${endtime:10:2}
    ENDS=${endtime:12:2}
    #
    echo ${channel}"_"${STARTH}"."${STARTM}"."${STARTS}"-"${ENDH}"."${ENDM}"."${ENDS}".dav"
    mv -f ${FNAME} ${channel}"_"${STARTH}"."${STARTM}"."${STARTS}"-"${ENDH}"."${ENDM}"."${ENDS}".dav"
  done