gpt4 book ai didi

bash - 如何迭代文件中的行并将字段读入变量

转载 作者:行者123 更新时间:2023-12-03 08:53:11 27 4
gpt4 key购买 nike

我有一个文件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 是否为真的部分,如果是,则 wget链接。这需要对文件的每一行单独完成。

最佳答案

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

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

  • date +%x 将在 $LC_TIME 环境变量中具有不同区域设置的系统上返回不同格式的日期。
    设置 LC_TIME=en_US 时,%x 格式将为 MM/DD/YYY,但存在很小的可能性(虽然不可否认可能性很小) 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

关于bash - 如何迭代文件中的行并将字段读入变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57608093/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com