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

时间:2019-04-24 03:59:35

标签: 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~

预先感谢

2 个答案:

答案 0 :(得分:0)

考虑到您的文件将没有未来的日期(按照您的示例显示),如果是这种情况,请尝试。

awk -v dat="$(date +%Y%m%d)" '
BEGIN{
  FS=OFS="*"
}
{
  split($4,array,"[-~]")
  if(array[1]!=dat){
    array[1]=dat
  }
  if(array[2]!=dat){
    array[2]=dat
  }
  $4=array[1]"-"array[2]"~"
}
1'   Input_file

答案 1 :(得分:0)

以下内容将在具有Bash和GNU的date实用程序的系统上工作。让我们使用“ 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
  

请您修改提供的脚本以用于目录中的所有文件。那对我很有帮助。

# 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
相关问题