我想验证output.txt
中的数据类型。
示例:
52 40.5 60 yes
30.3 20 40 no
结果:
52 is Integer
40.5 is Decimal
60 is Integer
Yes is Character
选择此任务应该更好 - bash
或awk
?
谢谢。
答案 0 :(得分:2)
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
答案 1 :(得分:2)
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
答案 2 :(得分:1)
使用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 read
读取一行(file.txt
,行在var REPLY
中)for
每个标记在行/ REPLY
)^..$
令牌)答案 3 :(得分:1)
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