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

标签 linux shell unix

我正在尝试编写一个脚本,它是一个 *(星号)分隔文件,有多行以 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/

相关文章:

linux - 如何获取目录的绝对路径?

linux - 需要将 AWS NFS 挂载移动到 Azure

shell - 导航到 ZSH 中的目录 (bash)

unix - SIGPIPE 的原因

c++ - 从 C++ 跳到 Perl/Unix 作业

php - 在php代码中用python导入caffe

c - 处理 TLB 未命中

linux - 为具有 = 的变量赋值,”

linux - 根据匹配模式将一行行 grep 到 shell 变量中

c - 在 Unix/Solaris 中验证用户名