我運行一個命令,getFiles輸出一個換行符分隔的串列檔案名。的輸出非常相似ls -1。檔案名都以代表一種時間戳的數字結尾。更大的數字是最近的。檔案名不遵循任何模式。例如file1234, other44234, something34142, carrot123.
我需要找到具有最大數字(數字)的檔案名。在這個例子other44234中。
找到檔案名后,我需要將其作為引數傳遞給另一個命令。IEdoItToIt "$THE_FILE"
uj5u.com熱心網友回復:
設定:
$ cat files.txt
file1234
other44234
something34142
carrot123
一個復雜的命令鏈:
$ sed -nE 's/^(.*[^0-9])([0-9] )$/\2 \1\2/p' files.txt | sort -nr | head -1 | awk '{print $2}'
other44234
但是一旦我們awk融入其中,就真的不需要其他任何東西了,例如:
awk '{ if (match($0,/([0-9] )$/)) { # if we find a string of numbers at the end of the line (aka filename)
sfx=substr($0,RSTART) # strip off the number and ...
if (sfx>max) { # if larger than the previous find then ...
max=sfx # make note of the new largest number and ...
fname=$0 # grab copy of current line (aka filename)
}
}
}
END { if (fname) print fname} # if fname is non-blank then print to stdout
' files.txt
這也會產生:
other44234
bash或者用一個正則運算式和BASH_REMATCH[]陣列來做整個事情:
regex="^.*[^0-9]([0-9] )$"
fname=""
max=0
while read -r f
do
[[ "${f}" =~ $regex ]] &&
[[ "${BASH_REMATCH[1]}" -gt "${max}" ]] &&
max="${BASH_REMATCH[1]}" &&
fname="${f}"
done < files.txt
這會產生:
$ typeset -p fname
declare -- fname="other44234"
uj5u.com熱心網友回復:
你正在尋找這樣的東西:
awk '{
tag = $0
sub(/^.*[^0-9]/, "", tag)
if (tag > max) {
max = tag
name = $0
}
}
END {
print name
}'
uj5u.com熱心網友回復:
另一種方式:
$ sed -E 's/^([a-Z] )([0-9] )/\1 \2/' files.txt |
sort -n -k2 |
tail -n1 |
tr -d ' '
other44234
uj5u.com熱心網友回復:
在純bash:
#!/bin/bash
maxnum=-1
while IFS= read -r fname; do
n=${fname##*[!0-9]}
if ((n > maxnum)); then
maxnum=$n
maxfile=$fname
fi
done < <(getFiles)
doItToIt "$maxfile"
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/520791.html
標籤:重击苹果系统脚本
上一篇:從檔案中讀取數字-每行3個數字-并將結果添加到BASH
下一篇:與bashfor回圈并行化
