I want to verify the type of data in output.txt.
example:
52 40.5 60 yes
30.3 20 40 no
result:
52 is Integer
40.5 is Decimal
60 is Integer
Yes is Character
What should be better to choose for this task - bash or awk?
Thank you.
awk '
BEGIN {
types["Integer"] = "^[[:digit:]]+$";
types["Decimal"] = "^[[:digit:]]+[.][[:digit:]]+$";
types["Character"] = "^[[:alpha:]]+$"
}
{
for (i = 1; i <= NF; i++) {
found = 0;
for (type in types) {
if ($i ~ types[type]) {
print $i, "is", type;
found = 1
}
}
if (! found) {
print "Type not found for:", $i
}
}
printf "\n"
}' inputfile
使用bash 模式
shopt -s extglob
while read line; do
set -- $line
for word; do
case $word in
?([-+])+([[:digit:]]) ) echo "$word is an integer" ;;
?([-+])@(*([[:digit:]]).+([[:digit:]])|+([[:digit:]]).*([[:digit:]])) ) echo "$word is a decimal" ;;
+([[:alpha:]]) ) echo "$word is alphabetical" ;;
*) echo "$word is a mixed string" ;;
esac
done
done < output.txt
使用 bash,您可以尝试以下操作:
#!/usr/bin/env bash
while read -r; do
for token in $REPLY; do # no quotes here!
if [[ "$token" =~ ^[[:digit:]]+$ ]]
then printf -- "%d is digit\n" "$token"
elif [[ "$token" =~ ^[[:digit:]]+\.[[:digit:]]+$ ]]
then printf -- "%f is float\n" "$token"
elif [[ "$token" =~ ^[[:alpha:]]+$ ]]
then printf -- "%s is string\n" "$token"
else printf -- "unknown class: %s\n" "$token"
fi
done
done < file.txt
while readfrom file.txt,行在 var 中REPLY)for行中的每个标记/ REPLY)^..$令牌与正则表达式和类匹配)TXR:一点点正则表达式,一点点类型系统。如果令牌看起来像一个数字,那么让我们尝试将其从字符串转换为数字对象num-str。如果失败,则一定是范围错误。该typeof函数为我们提供了对象的类型fixnum:bignum或float。
@(freeform)
@(coll)@{token /[^\s]+/}@(end)
@(output)
@ (repeat)
@token @(if (eql (match-regex token #/[+\-]?\d+([.]\d+)?([Ee][+\-]?\d+)?/)
(length token))
(let ((x (num-str token)))
(if x (typeof x) "out-of-range"))
"non-numeric")
@ (end)
@(end)
跑:
$ txr verify.txr -
hello world
1.5E900 1.43 52 5A 12341234123412341234 12341234123412341234243.42 42
[Ctrl-D]
hello non-numeric
world non-numeric
1.5E900 out-of-range
1.43 float
52 fixnum
5A non-numeric
12341234123412341234 bignum
12341234123412341234243.42 float
42 fixnum