gpt4 book ai didi

linux - Unix 脚本在目录中存在的多个文件中动态地用当前日期替换旧日期

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

我正在尝试编写一个脚本,它是一个 *(星号)分隔文件,有多行以 DTP 开头。我想对日期部分进行子串并与今天的日期进行比较。如果它比今天早,我想用今天的日期替换。这是一个例子。

$ cat temp.txt
RTG*888*TD8*20180201-20180201~
TWW*888*RD8*20180201-20180201~
RTG*888*TD8*20180201-20180201~
KCG*888*TD8*20180201-20180201~

我希望通过更改日期得到如下输出。请帮忙。我正在寻找 UNIX 脚本以使其适用于该目录中存在的所有文件

RTG*888*TD8*20190424-20190424~
TWW*888*RD8*20180201-20180201~
RTG*888*TD8*20190424-20190424~
KCG*888*TD8*20180201-20180201~

提前致谢

最佳答案

以下内容适用于具有 Bash 和 GNU 日期实用程序的系统。让我们使用“while read”循环编写一个简单的脚本:

# read the file line by line with fields separated by *
while IFS='*' read -r str1 num str2 date; do
# if the first field is RTG
if [ "$str1" = "RTG" ]; then
# then substitute date with current date string
curdate=$(date +%Y%m%d)
date="${curdate}-${curdate}~"
fi
# print the output
printf "%s*%s*%s*%s\n" "$str1" "$num" "$str2" "$date"
# in while read loops - the input file is
# redirected to standard input on the end
done < file.txt

Could you please modify the script you provided to work for all files in directory. That would be very helpful for me .

# for all entries in current directory (uses bash globulation settings(!))
for file in *; do
# check if it's a file
if [ ! -f "$file" ]; then
# if not, next entry
continue;
fi

# run the script
while IFS='*' read -r str1 num str2 date; do
if [ "$str1" = "RTG" ]; then
curdate=$(date +%Y%m%d)
date="${curdate}-${curdate}~"
fi
printf "%s*%s*%s*%s\n" "$str1" "$num" "$str2" "$date"
done < "$file"

done

关于linux - Unix 脚本在目录中存在的多个文件中动态地用当前日期替换旧日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55822214/

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