验证数据类型

时间:2012-05-16 09:22:22

标签: bash shell awk

我想验证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

选择此任务应该更好 - bashawk

谢谢。

4 个答案:

答案 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)

使用bash patterns

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函数为我们提供了对象的类型:fixnumbignumfloat

@(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