首页 > 解决方案 > 如何迭代文件中的行并将字段读入变量

问题描述

我有一个hotfix_final看起来像这样的文件:

https://download.abc.com  06/24/2019
https://download.abc.com  06/26/2019
https://download.abc.com  07/05/2019

我需要编写一个 shell 脚本,逐行读取文件,然后将链接旁边的日期放入一个变量中,以便我可以将其与当前日期进行比较。如果日期相等并且usage_type = 4,我需要脚本来获取链接。

到目前为止我尝试了什么:

usage_type=$( cat /opt/abc/ps/usage.txt )
current_date=$( date +%x )
lines=$( wc -l /home/abc/hotfix_final | awk '{print $1}' )

count=0

while $count <= $lines; do

    hf_link=$( awk if( NR=$count ) '{print $1}' hotfix_final )
    relase_date=$( awk if( NR=$count ) '{print $2}' hotfix_final )
    count=$(( count+1 ))

done < hotfix_final

在上面的例子中,我使用了:

现在,我不确定如何编写检查是否为真的部分$usage_type == 4$current_date = $relase_date 如果是,请获取链接。这需要为文件的每一行单独完成。

标签: bashshellloopsawk

解决方案


可以通过对脚本进行一些修复来完成:

  • 您需要注意引用变量以避免值在空格或$IFS变量中列出的任何字符上被拆分。

  • date +%x$LC_TIME将在环境变量中具有不同语言环境设置的系统上返回具有不同格式的日期。设置时
    %x格式是,但是系统可能无法使用区域设置的可能性很小(虽然公认的可能性很小) 。 然后最好使用明确的独立于语言环境的格式, 以保证日期格式的安全。MM/DD/YYYLC_TIME=en_USen_US
    +%d/%m/%Y

这是一个固定版本:

#!/usr/bin/env bash
# Early exit this script if the usage.txt file does not contain the value 4
grep -Fqx 4 /opt/abc/ps/usage.txt || exit

# Store current date in the MM/DD/YYYY format
current_date="$(date +%d/%m/%Y)"

# Iterate each line from hotfix_final
# and read the variables hf_link and release_date
while read -r hf_link release_date; do
  if [ "$current_date" = "$release_date" ]; then
    wget "$hf_link"
  fi
done </home/abc/hotfix_final # Set the file as input for the whole while loop

推荐阅读