我需要在使用 ksh 时将日期和主机名插入到行尾。这些行是 vmstat 操作系统的输出,如果一行以数字开头,我需要将日期和主机名添加到该行的末尾:
我有这个测试脚本:
#!/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
最佳答案
您似乎使用了 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
关于unix - 无法在 korn 脚本中的每行末尾插入日期和主机名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16401192/