bash - 如何迭代文件中的行并将字段读入变量
问题描述
我有一个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
如果是,请获取链接。这需要为文件的每一行单独完成。
解决方案
可以通过对脚本进行一些修复来完成:
您需要注意引用变量以避免值在空格或
$IFS
变量中列出的任何字符上被拆分。date +%x
$LC_TIME
将在环境变量中具有不同语言环境设置的系统上返回具有不同格式的日期。设置时
的%x
格式是,但是系统可能无法使用区域设置的可能性很小(虽然公认的可能性很小) 。 然后最好使用明确的独立于语言环境的格式, 以保证日期格式的安全。MM/DD/YYY
LC_TIME=en_US
en_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
推荐阅读
- ios - 如何从 Swift 包中只导入一个特定的库?
- javafx - 更新 JavaFX 状态标签
- javascript - 显示来自 JSON 响应的嵌套对象
- pdf - 需要使用 VFP 代码在 VFP Windows 中显示 PDF 文件
- node.js - 我可以将 npm node_modules 目录放在我的项目之外吗
- c - 什么是正确的选择?它的 C 在我提到的来源中提到。但我觉得它的d
- python - 如何加入当前行时间之前的最近时间(Pyspark 2.4.4 Dataframes)
- c - 如何使用 if 语句从文件中获取?
- etl - 在 ETL 脚本中使用 DDL 语句是否正确?
- python - 学校任务所需的帮助