如何解决重命名带有嵌入日期的按顺序命名的文件
情况:
我有数百个 zip 文件,其名称中混有任意日期/时间 (4-6-2021 12-34-09 AM.zip
)。我需要在 Linux cli 系统中按顺序获取所有这些文件(0.zip、1.zip 2.zip 等)。
我尝试过的:
我试过 ls -tr | while read i; do n=$((n+1)); mv -- "$i" "$(printf '%03d' "$n").zip"; done
几乎可以做我想要的,但似乎仍然没有顺序(我认为它采用文件创建时间的顺序而不是文件名(这是我需要的) ).
如果我能做到这一点,我的下一步就是将每个 zip 中的文件(是单个文件)重命名为 zip 文件的名称。我也不知道我会怎么做。
tl;博士
我用奇怪的日期系统命名了这些文件。我需要按顺序排列日期并按顺序重命名,如 0.zip 1.zip 2.zip etc
。现在是凌晨 3:00,我不知道为什么我还在尝试解决这个问题,我不知道如何将 zip 中的文件重命名为该序列号(阅读上面的更多详细信息)。
提前致谢!
解决方法
GNU awk 是这里的一个选项,将文件列表的结果重定向回 awk:
awk '{
fil=$0; # Set a variable fil to the line
gsub("-"," ",$1); # Replace "-" for " " in the first space delimited field
split($1,map," "); # Split the first field into the array map,using " " as the delimiter
if (length(map[1])==1) {
map[1]="0"map[1] # If the length of the day is 1,pad out with "0"
};
if (length(map[2])==1) {
map[2]="0"map[2] # Do the same for month
}
$1=map[1]" "map[2]" "map[3]; # Rebuilt first field based on array values
gsub("-",$2); # Change "-" for " " in time
map1[mktime($1" "$2)]=fil # Get epoch format of date/time using mktime function and use this as an index for array map1 with the original line (fil) as the value
}
END {
PROCINFO["sorted_in"]="@ind_num_asc"; # At the end of processing,set the array sorting to index number ascending
cnt=0; # Initialise a cnt variable
for (i in map1) {
print "mv \""map1[i]"\" \""cnt".zip\""; # Loop through map1 array printing values and using these values along with cnt to generate and print move command
cnt++
}
}' <(for fil in *AM.zip;do echo $fil;done)
一旦您对打印命令的打印方式感到满意,就将结果通过管道传输到 bash 中,然后:
awk '{ fil=$0;gsub("-",$1);split($1," ");if (length(map[1])==1) { map[1]="0"map[1] };if (length(map[2])==1) { map[2]="0"map[2] }$1=map[1]" "map[2]" "map[3];gsub("-",$2);map1[mktime($1" "$2)]=fil} END { PROCINFO["sorted_in"]="@ind_num_asc";cnt=0;for (i in map1) { print "mv \""map1[i]"\" \""cnt".zip\"";cnt++ } }' <(for fil in *AM.zip;do echo $fil;done) | bash
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。