我的檔案都按照約定命名:xxx_yyy_zzz_ooo_date_ppp.tif
我有一個需要 3 個輸入的 python 函式:檔案夾中兩個連續檔案的日期,以及從這兩個日期生成的輸出名稱。
我創建了一個回圈:
- 遍歷檔案夾中的每個檔案
- 獲取檔案的日期并將其分配給一個變數(“file2”,檔案名中的第 5 位)
- 運行一個將輸入作為輸入的 python 函式:日期檔案 1、日期檔案 2、輸出名稱
如何讓我的回圈從檔案夾中的第二個檔案開始,并獲取前一個檔案的名稱以將其分配給變數“file1”(到目前為止它一次只獲取 1 個檔案的日期)?
#!/bin/bash
output_path=path # Folder in which my output will be saved
for file2 in *; do
f1=$( "$file1" | awk -F'[_.]' '{print $5}' ) # File before the one over which the loop is running
f2=$( "$file2" | awk -F'[_.]' '{print $5}' ) # File 2 over which the loop is running
outfile=$output_path $f1 $f2
function_python -$f1 -$f2 -$outfile
done
uj5u.com熱心網友回復:
你可以讓它像這樣作業:
#!/bin/bash
output_path="<path>"
readarray -t files < <(find . -maxdepth 1 -type f | sort) # replaces '*'
for ((i=1; i < ${#files[@]}; i )); do
f1=$( echo "${files[i-1]}" | awk -F'[_.]' '{print $5}' ) # previous file
f2=$( echo "${files[i]}" | awk -F'[_.]' '{print $5}' ) # current file
outfile="${output_path}/${f1}${f2}"
function_python -"$f1" -"$f2" -"$outfile"
done
function_python不過,我不確定對 的呼叫,我以前從未見過該工具(無法詢問,因為我還不能發表評論)。
uj5u.com熱心網友回復:
將檔案讀入陣列,然后從索引 1 開始迭代,而不是遍歷整個陣列。
#!/bin/bash
set -euo pipefail
declare -r output_path='/some/path/'
declare -a files fsegments
for file in *; do files =("$file"); done
declare -ar files # optional
declare -r file1="${files[0]}"
IFS=_. read -ra fsegments <<< "$file1"
declare -r f1="${fsegments[4]}"
for file2 in "${files[@]:1}"; do # from 1
IFS=_. read -ra fsegments <<< "$file2"
f2="${fsegments[4]}"
outfile="${output_path}${f1}${f2}"
function_python -"$f1" -"$f2" -"$outfile" # weird format!
done
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/336409.html
下一篇:從for回圈創建串列
