SHELL16. 判断输入的是否为IP地址
描述
192.168.1.1
192.168.1.0
300.0.0.0
123
yesyesnoerror
Bash 解法, 执行用时: 2ms, 内存消耗: 424KB, 提交时间: 2021-12-20
#!/bin/bash while read line do arr=(${line//./ }) if [ ${#arr[*]} -ne 4 ];then printf "error\n" else for((i=0;i<${#arr[*]};i++)) do [ ${arr[${i}]} -gt 255 ] && printf "no\n" && break done [ $i == 4 ] && printf "yes\n" fi done < nowcoder.txt
Bash 解法, 执行用时: 2ms, 内存消耗: 436KB, 提交时间: 2022-02-09
# copied from discussion while read line do arr=(${line//./ }) if [ ${#arr[*]} -ne 4 ];then printf "error\n" else for ((i=0; i<${#arr[*]}; i++)) do [ ${arr[${i}]} -gt 255 ] && printf "no\n" && break done [ $i == 4 ] && printf "yes\n" fi done
Bash 解法, 执行用时: 3ms, 内存消耗: 400KB, 提交时间: 2022-02-28
# awk -F "." '{ # if (NF == 4) { # for (i = 1;i < 5;i++) { # if ($i > 255 || $i < 0) { # print("no");break; # } # } # if (i == 5) {print("yes")} # } else { # print("error") # } # }' while read line do sum=0 IFS=. arr=($line) if [ ${#arr[@]} -lt 4 ] then echo 'error' else for i in ${arr[@]} do if [ $i -ge 0 -a $i -le 255 ] then ((sum+=1)) fi done if [ $sum -eq 4 ] then echo 'yes' else echo 'no' fi fi done < nowcoder.txt
Bash 解法, 执行用时: 3ms, 内存消耗: 408KB, 提交时间: 2021-12-20
# awk '{ # if ($0 ~ /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[09][0-9]|[1-9][0-9]|[0-9])$/) { # print("yes"); # } else if ($0 ~ /[[:digit:]].[[:digit:]].[[:digit:]].[[:digit:]]/){ # print("no"); # } else { # print("error") # } # }' nowcoder.txt # awk -F '.' '{ # if (NF == 4) { # for (i = 1; i < 5; i++) { # if ($i > 255 || $i < 0) { # print("no") # break # } # } # if (i == 5) { # print("yes") # } else { # print("error") # } # } # }' IFS='.' while read line; do arr=(${line}) if [ ${#arr[*]} -ne 4 ]; then printf "error\n" else for ((i = 0; i < ${#arr[*]}; i++)); do if [ ${arr[${i}]} -gt 255 ]; then printf "no\n" break fi done # if [ $i == 4 ]; then # printf "yes\n" # fi [ $i == 4 ] && printf "yes\n" fi done
Bash 解法, 执行用时: 3ms, 内存消耗: 412KB, 提交时间: 2022-02-25
IFS='.' while read line; do arr=(${line}) if [ ${#arr[*]} -ne 4 ]; then printf "error\n" else for ((i = 0; i < ${#arr[*]}; i++)); do if [ ${arr[${i}]} -gt 255 ]; then printf "no\n" break fi done [ $i == 4 ] && printf "yes\n" fi done