我有一个Shell脚本,可以给我一个包含某些数字的txt文件。 例如,“ 48 347 345 221 1029 3943 1245 7899”。 它仅包含一行。
如果其中一个数字超过500,我想触发另一个shell脚本。 如何比较数字并运行Shell脚本? 预先感谢
cat text.txt | if [ awk '{print $1}' -ge 500 ] then command.sh fi
答案 0 :(得分:0)
使用awk
,您可以尝试以下操作:
awk '{for(i=1;i<=NF;i++)if($i > 500)exit 1}' text.txt || ./command.sh
如果由于command.sh
运算符而导致awk
命令以非零代码退出,则会执行 ||
。
答案 1 :(得分:0)
将文件内容放入数组-
$: declare -a lst=( $(<text.txt) )
然后运行一个快速循环。如果您想为每次匹配运行命令,
$: for n in "${lst[@]}"
do (( n > 500 )) && echo "command.sh # $n > 500"
done
command.sh # 1029 > 500
command.sh # 3943 > 500
command.sh # 1245 > 500
command.sh # 7899 > 500
如果您只想要一个快速而肮脏的版本,
$: for n in $(<text.txt); do (( n > 500 )) && command.sh; done
但是我建议您花些时间执行极其复杂的 2 步骤,大声笑
如果任何数超过500,则只运行一次,
$: for n in "${lst[@]}"
do (( n > 500 )) && { echo "command.sh # $n > 500"; break; }
done
command.sh # 1029 > 500
不要那样用猫。尽量不要像那样使用猫。
如果您* REALLY需要该文件作为if
的输入,请执行以下操作:
if condition
then action
fi < text.txt
答案 2 :(得分:0)
您可以使用一个简单的for循环,如下所示:
for n in $(cat test.txt)
do
if [ $n -gt 500 ]; then
something.sh
fi
done
答案 3 :(得分:0)
您可以简单地:
[[ "48 347 345 221 500" =~ ([ ][5-9][0-9][0-9]|[ ][1-9][0-9]{3,}) ]] && echo "Hi"
Hi
[[ "48 347 345 221" =~ ([ ][5-9][0-9][0-9]|[ ][1-9][0-9]{3,}) ]] && echo "Hi"
希望这会有所帮助!
答案 4 :(得分:0)
当您不想将小数转换为数字时,它将变得很讨厌。
寻找至少4位数字(前一位不是0)或3位数字,前5位或更高的数字会给出
# incorrect, includes 500
grep -Eq "([1-9][0-9]|[5-9])[0-9][0-9]" text.txt && command.sh
这还将执行编号为500的command.sh
。
# incorrect, will fail for 5000 and 1500
grep -E "([1-9][0-9]|[5-9])[0-9][0-9]" text.txt | grep -qv 500 && command.sh
修复它变得太复杂了。 awk
似乎是最自然的方法。
人工的方式是将输入转换为具有一个数字的行,并在边框处添加额外的行:
(echo "500 border"; tr ' ' '\n' < text.txt) |
sort -n |
tail -1 |
grep -qv "border" && command.sh