我想验证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
?
谢谢。
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 digitn" "$token"
elif [[ "$token" =~ ^[[:digit:]]+.[[:digit:]]+$ ]]
then printf -- "%f is floatn" "$token"
elif [[ "$token" =~ ^[[:alpha:]]+$ ]]
then printf -- "%s is stringn" "$token"
else printf -- "unknown class: %sn" "$token"
fi
done
done < file.txt
- 读取一行(从
file.txt
while read
,行在变量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