简体   繁体   English

在bash中转换日期格式

[英]Converting date format in bash

I have similar different file of the format backup_2016-26-10_16-30-00 is it possible to rename using bash script to backup_26-10-2016_16:30:00 for all files. 我有类似的不同文件,格式为backup_2016-26-10_16-30-00 ,是否可以使用bash脚本将所有文件重命名为backup_26-10-2016_16:30:00 Kindly suggest some method to fix this. 请提出一些解决此问题的方法。

Original file: 原始文件:

backup_2016-30-10_12-00-00

Expected output: 预期产量:

backup_30-10-2016_12:00:00

To perform only the name transformation, you can use awk : 要仅执行名称转换,可以使用awk

echo 'backup_2016-30-10_12-00-00' |
  awk -F'[_-]' '{ print $1 "_" $3 "-" $4 "-" $2 "_" $5 ":" $6 ":" $7 }'

As fedorqui points out in a comment, awk 's printf function may be tidier in this case: 正如fedorqui在评论中指出的,在这种情况下, awkprintf函数可能更简洁:

echo 'backup_2016-30-10_12-00-00' |
  awk -F'[_-]' '{ printf "%s_%s-%s-%s_%s:%s:%s\n", $1,$3,$4,$2,$5,$6,$7 }'

That said, your specific Linux distro may come with a rename tool that allows you to do the same while performing actual file renaming. 也就是说,您的特定Linux发行版可能附带一个rename工具,使您可以在执行实际文件重命名时执行相同的操作。

with perl based rename command: 使用基于perlrename命令:

$ touch backup_2016-30-10_12-00-00 backup_2016-26-10_16-30-00

$ rename -n 's/(\d{4})-([^_]+)_(\d+)-(\d+)-/$2-$1_$3:$4:/' backup*
rename(backup_2016-26-10_16-30-00, backup_26-10-2016_16:30:00)
rename(backup_2016-30-10_12-00-00, backup_30-10-2016_12:00:00)

remove the -n option for actual renaming 删除-n选项以进行实际重命名

rename is for this task rename用于此任务

$ rename 's/_(\d{4})-(\d\d-\d\d)_(\d\d)-(\d\d)-(\d\d)$/_$2-$1_$3:$4:$5/' backup_2016-30-10_12-00-00

but not sure will be simpler 但不确定会更简单

you can also this script; 您也可以使用此脚本;

#!/bin/bash
fileName=$1
prefix=$(echo ${fileName} | cut -d _ -f1)
date=$(echo ${fileName} | cut -d _ -f2)
time=$(echo ${fileName} | cut -d _ -f3)

year=$(echo ${date} | cut -d - -f1)
day=$(echo ${date} | cut -d '-' -f2)
month=$(echo ${date} | cut -d '-' -f3)

formatedTime=$(echo $time |  sed 's/-/:/g')

formatedDate=$day"-"$month"-"$year

formatedFileName=$prefix"_"$formatedDate"_"$formatedTime

echo $formatedFileName

Eg; 例如;

user@host:/tmp$ ./test.sh backup_2016-30-10_12-00-00
backup_30-10-2016_12:00:00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM