【发布时间】:2019-12-27 16:54:42
【问题描述】:
我有一个文件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
在上面的例子中,我使用了:
$lines显示要读取的最大行数。$hf_link获取链接$release_date获取 $hf_link 旁边的日期
现在,我不确定如何编写检查$usage_type == 4 和$current_date = $relase_date 是否为真的部分,如果是,请获取链接。这需要为文件的每一行单独完成。
【问题讨论】:
-
这个脚本有很多很多很多的错误。 (1):正确引用您的 awk:
awk '{if( NR==$count ) print $1}'(2) 如果语句应该进行比较而不是赋值:if(NR == $count)(3) shell 变量应该正确地传递给 awk:awk -v count=$count '{if(NR == count) print $1}'(4) 不要像你那样用 while 循环解析 bash 中的文件:,只需使用适当的 while 与 read 结合,您可以跳过 awk 来提取变量。查看Léa Gris的回答 -
请参阅stackoverflow.com/a/38627863/874188,了解为什么读取行号通常是一种反模式。