[英]Bash read parameters from file
我有一個帶有 days 參數的 parameters.txt ,用於存儲一個月中的不同天數。
Days: 1,5,31
我想創建一個 bash 腳本,該腳本將讀取參數“Days”並將以“,”分隔的日期與當前日期進行比較。 如果當前日期等於其中一天,它將回顯“true”。
但是我遇到了一些麻煩:如何從 bash 腳本中讀取 days 參數,並每天讀取並與當天進行比較? 我成功地閱讀了整行
, ,
此外,當我嘗試使用 $d 獲取當前日期時,我會得到類似 01 ,02 等的日期。 但在我的參數中,天數是 1 , 2 ...
如果您可以控制此文件,則更好的格式是每行一個數字,或者可能是僅由數字組成的以空格分隔的行。
如果沒有,您可以使用簡單的 Awk 代碼段將這種邪惡的格式預處理為更容易使用 shell 腳本處理的格式。
awk '/^Days: / {
n = split($2, d, /,/)
for (i=1; i<=n; ++i) print d[i] }' parameters.txt |
while read -r number; do
date -d "$number days ago"
done
這應該這樣做:
#!/bin/bash
filename="parameters.txt"
while read -r line; do
# Look for the correct line (if you have other parameters)
if [[ $line == Days:* ]]; then
# Remove line prefix
days=$(echo "$line" | cut -c 7-);
# Change the delimiter
IFS=', ';
read -ra arr <<< "$days"
for i in "${arr[@]}"; do
# Check for current day
if (( $(date +%d) == i ));
then echo "Found current day";
fi;
done;
fi;
done < $filename
請注意,如果您必須在腳本中進行其他read
,更改IFS
可能會給您帶來一些問題,在這種情況下,我建議您將其更改回其原始值。
如果您的parameters.txt
僅包含您可以執行的 days 參數
#!/bin/bash
filename="parameters.txt"
# Remove line prefix
days=$(cut "$filename" -c 7-);
# Change the delimiter
IFS=', ';
# etc ...
awk 'BEGIN {
split(strftime(),dat," ");
day=dat[3]
}
/^Days/ {
split($2,arr,",");
for (i in arr)
{
if (day ==arr[i])
{
print "True"
}
}
}' parameters.txt
單線
awk 'BEGIN {split(strftime(),dat," ");day=dat[3]} /^Days/ { split($2,arr,",");for (i in arr) { if (day ==arr[i]) { print "True" } } }' parameters.txt
我們首先使用 awk 的 strftime 函數獲取今天的日期,然后使用 awk 的 split 函數將其進一步拆分為 dat 數組,並使用“”作為分隔符。 然后我們將 day 設置為數組的第三個索引。 然后當我們遇到以 Days 開頭的行時,我們將空格($2)之后的部分以逗號為分隔符分割成一個數組 arr。 然后我們循環遍歷這個數組,將天數與當前天進行比較,如果匹配則打印 True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.