给定一个包含多个单词的字符串,如下所示,全部在一行中:
first-second-third-201805241346 first-second-third-201805241348 first-second-third-201805241548 first-second-third-201705241540
我正在尝试字符串中的最大数字,在这种情况下答案应为201805241548
我尝试过使用awk和grep,但我只是在字符串中得到答案。
我对如何实现这一目标很感兴趣。
答案 0 :(得分:3)
echo 'first-second-third-201805241346 first-second-third-201805241348 first-second-third-201805241548 first-second-third-201705241540' |\
grep -o '[0-9]\+' | sort -n | tail -1
相关部分为grep -o '[0-9]\+' | sort -n | tail -n 1
。
答案 1 :(得分:2)
使用单gnu awk
命令:
s='first-second-third-201805241346 first-second-third-201805241348 first-second-third-201805241548 first-second-third-201705241540'
awk -F- -v RS='[[:blank:]]+' '$NF>max{max=$NF} END{print max}' <<< "$s"
201805241548
或使用grep + awk
(如果gnu awk
不可用):
grep -Eo '[0-9]+' <<< "$s" | awk '$1>max{max=$1} END{print max}'
答案 2 :(得分:1)
另一个awk
echo 'first-...-201705241540' | awk -v RS='[^0-9]+' '$0>max{max=$0} END{print max}'
答案 3 :(得分:1)
Gnarly pure bash
:
n='first-second-third-201805241346 \
first-second-third-201805241348 \
first-second-third-201805241548 \
first-second-third-201705241540'
z="${n//+([a-z-])/;p=}"
p=0 m=0 eval echo -n "${z//\;/\;m=\$((m>p?m:p))\;};m=\$((m>p?m:p))"
echo $m
输出:
201805241548
工作原理:此代码构造代码,然后运行它。
z="${n//+([a-z-])/;p=}"
substitutes带有一些预编码的非数字
- 将$p
设置为每个数字的值,(单独无用)。此时echo $z
将输出:
;p=201805241346 \ ;p=201805241348 \ ;p=201805241548 \ ;p=201705241540
将添加的;
替换为更多代码,将$m
设置为
$p
的最大值,需要eval
才能运行它 - 实际值
使用eval
运行的整行代码如下:
p=0 m=0
m=$((m>p?m:p));p=201805241346
m=$((m>p?m:p));p=201805241348
m=$((m>p?m:p));p=201805241548
m=$((m>p?m:p));p=201705241540
m=$((m>p?m:p))
打印$m
。