无法在korn脚本中的每一行末尾插入日期和主机名

时间:2013-05-06 14:42:51

标签: unix ksh

我需要在使用ksh时将日期和主机名插入到行尾。这些行是从vmstat os输出的,如果一行以数字开头,我需要将Date和Hostname添加到该行的末尾:

我有这个测试脚本:

#!/usr/bin/ksh

  while read line
  do
    printf "$line"
    if [[ "$line" =~ "^([0-9])" ]]; then
       date '+ %m-%d-%Y %H:%M:%S'
       hostname
    else
       echo
    fi
  done

当我这样做时

vmstat 3 | test



syntax error at line 6 : `=~' unexpected

1 个答案:

答案 0 :(得分:3)

您似乎使用ksh的实现,该实现不知道=~运算符,例如ksh88

你可以诉诸于grep进行匹配,例如

test.sh

#!/bin/ksh

while read line; do
    printf "$line"
    if echo "${line}" | grep -q "^[0-9]"; then
        printf "%s %s" "$(
            date '+ %m-%d-%Y %H:%M:%S'
        )" "$(hostname)"
    fi
    echo
done

示例运行:

$ printf "foo\n3 bar\nquux\n" | ./test.sh
foo
3 bar 05-06-2013 18:53:59 myhostname
quux
相关问题