gpt4 book ai didi

linux - 如何用当前日期替换文件名中的日期部分

转载 作者:太空宇宙 更新时间:2023-11-04 05:59:29 34 4
gpt4 key购买 nike

如何仅将日期部分替换为 unix 目录中所有文件的当前日期。

文件夹路径: C:/shan

示例文件:

CN_Apria_837p_20180924.txt  
DN_Apria_837p_20150502.txt
GN_Apria_837p_20160502.txt
CH_Apria_837p_20170502.txt
CU_Apria_837p_20180502.txt
PN_Apria_837p_20140502.txt
CN_Apria_837p_20101502.txt

期望的结果应该是:

CN_Apria_837p_20190502.txt  
DN_Apria_837p_20190502.txt
GN_Apria_837p_20190502.txt
CH_Apria_837p_20190502.txt
CU_Apria_837p_20190502.txt
PN_Apria_837p_20190502.txt
CN_Apria_837p_20190502.txt
<小时/>

编辑:

我对 UNIX 销售脚本完全陌生。我在下面尝试了这个,但它不起作用。

#!/bin/bash

for i in ls $1 | grep -E '[0-9]{4}-[0-9]{2}-[0-9]{2}'
do
x=echo $i | grep -oE '[0-9]{4}-[0-9]{2}-[0-9]{2}'
y=echo $i | sed "s/$x/$(date +%F)/g"
mv $1/$i $1/$y 2>/dev/null #incase if old date is same as current date
done

最佳答案

我会在这里使用正则表达式。来自 bash 手册页:

An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3)). The return value is 0 if the string matches the pattern, and 1 otherwise. .... Substrings
matched by parenthesized subexpressions within the regular expression are saved in the array variable BASH_REMATCH. ... The element of BASH_REMATCH with indexn is the portion of the string matching the nth parenthesized sub-expression.

因此,假设变量 x 保存其中一个文件的名称有问题的代码

if [[ $x =~ ^(.*_)[0-9]+([.]txt$) ]]
then
mv "$x" "$BASH_REMATCH[1]$(date +%Y%m%d)$BASH_REMATCH[2]"
fi

首先粗略测试文件是否确实遵循所需的命名方案,然后相应地修改名称。

当然,在实践中,您将定制正则表达式以更好地匹配您的应用程序。只有您才能知道允许使用哪些文件名变体。

关于linux - 如何用当前日期替换文件名中的日期部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55948335/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com