我想从ls
输出中提取一组2位数字,并能够从中获取最大和最小的数字,供以后使用。
我这样做:
ls 14_data_*.log | egrep -o '[0-9]{2,2}' | head -1}
但输出有时只是按升序排列,而head
,tail
期望返回错误的值。我尝试将它转换为整数但无望。
ls
返回了什么以及如何处理?
答案 0 :(得分:2)
ls
返回当前目录中的文件和目录列表。
我不知道你在做什么,但这是使用sort
解决问题的方法:
降序:
ls 14_data_*.log | egrep -o '[0-9]{2}' | sort -nr
升序:
ls 14_data_*.log | egrep -o '[0-9]{2}' | sort -n
答案 1 :(得分:1)
我真的不认为你需要在这里使用ls
。如果您确定您的文件名不包含换行符,则可以使用:
printf '%s\n' 14_data_*.log | grep -Eo '[0-9]{2}'
然后将其传递到sort -n
,-r
以反转排序顺序。
答案 2 :(得分:0)
I believe this is an XY problem.
How I understand what you want: you have some files in the current directory that match the glob 14_data_[0-9][0-9].log
. And you want to extract the smallest and highest number from the glob [0-9][0-9]
.
E.g., given the listing
14_data_1.log
14_data_09.log
14_data_13.log
14_data_87.log
14_data_aa.log
you want the numbers 09
and 87
, as min and max respectively.
Here's a simple pure Bash way to achieve this:
shopt -s nullglob
files=( 14_data_[0-9][0-9].log )
fnumbers=( "${files[@]#14_data_}" )
fnumbers=( "${fnumbers[@]%.log}" )
if (( ${#fnumbers[@]} == 0 )); then
echo "No files found."
else
printf 'min=%d\nmax=%d\n' "$((10#${numbers[0]}))" "$((10#${numbers[-1]}))"
fi
shopt -s nullglob
: make globs expand to nothing if no matchesfiles=( 14_data_[0-9][0-9].log )
: populate an array files
with all matching filesfnumbers=( "${files[@]#14_data_}" )
: populate an array fnumbers
with the fields of files
where the leading 14_data_
is removedfnumbers=( "${fnumbers[@]%.log}" )
: and remove the trailing .log
from this arrayAt this point, you have an array fnumbers
that contains (in the example case): ( 09 13 87 )
.
We finally select the first and last elements of this array to get the lowest and highest number.