如何将bash函数用于日期值

时间:2015-01-05 08:06:56

标签: bash function

我有这样的日志文件(xferlog):

Mon Jan  5 09:52:58 2015 1 10.0.0.1 0 /home/DATA1/123.sqlLdr b _ i r DATA1 ftp 0 * c

我需要所有模式的ftp转移日期(最后一次转移),如下所示:

201501050952 ( yearmonthdayhourminute )

我可以这样做:

xfer1=$(tac "/var/log/xferlog" | awk -v pattern="DATA1" '$9 ~ pattern {print; exit}')

day1=${xfer1:8:2}
month1=${xfer1:4:3}
year1=${xfer1:20:4}
hour1=${xfer1:11:2}
minute1=${xfer1:14:2}

# For converting Jan, Feb... --> 01, 02

if [ "$month1" == "Jan" ];then
month1=01
fi
if [ "$month1" == "Feb" ];then
month1=02
...

# For converting month - 1,2,3 --> 01, 02, 03

day1s=$day1
if [ "$day1" == " 1" ];then
day1s=01
fi
if [ "$day1" == " 2" ];then
day1s=02
fi
...

echo "DATA1: $year1$month1$day1s$hour1$minute1"
...

它的工作,但我需要为其他模式做同样的过程。像这样:

xfer1=$(tac "/var/log/xferlog" | awk -v pattern="DATA1" '$9 ~ pattern {print; exit}')
xfer2=$(tac "/var/log/xferlog" | awk -v pattern="LIN5" '$9 ~ pattern {print; exit}')
...

如何使用函数转换日期格式并使用所有模式?我如何在函数中使用变量?我可以做不同的变量名称和转换(day1 day2 day3 ...),但它太长而且不常见。

2 个答案:

答案 0 :(得分:1)

你可以使用Python,我希望它相当不言自明。我已经对它进行了编辑,实际上是将其作为一个" Bash"嵌入Python脚本的代码片段。

tac "/var/log/xferlog" | python -c "
import datetime
import fileinput

for line in fileinput.input():
    path = line.split()[8]
    user = path.split('/')[2]
    if user in ('DATA1', 'LIN5'):
        dt = datetime.datetime.strptime(line[:24], '%a %b %d %H:%M:%S %Y')
        print dt.strftime('%Y%m%d%H%M')
"

答案 1 :(得分:1)

对你已经拥有的模式进行循环是一个明智的选择。

for pat in DATA1 LIN5; do
    xfer=$(tac /var/log/xferlog |
        awk -v pattern="$pat" '$9 ~ pattern { print; exit }')
    : massive ugly date processing here
    echo "$PAT: $year1$month1$day1s$hour1$minute1"
done

您也可以轻松地将日期处理分解为Awk脚本。

for pat in DATA1 LIN5; do
    tac /var/log/xferlog |
    awk -v pattern="$pat" 'BEGIN {
        m="Jan:Feb:Mar:Apr:May:Jun:Sep:Oct:Nov:Dec";
        n=split(m, mm, /:/); for (i=1; i<=n; i++) month[mm[i]]=i; }
        $9 ~ pattern { printf("%s: %04i%02i%02i%02i%02i\n", pattern,
            substr($0, 21, 4), month[substr($0, 5, 3)], 0+substr($0, 9, 2),
            substr($0, 12,2), substr($0, 15, 2)); exit }'
done

为了提高处理效率,您还可以将模式分解为Awk脚本。记住模式列表并在找到所有模式后退出是一个很小的复杂因素。

tac /var/log/xferlog |
awk 'BEGIN { pat["DATA"]=1; pat["LIN5"]=1; 
    m="Jan:Feb:Mar:Apr:May:Jun:Sep:Oct:Nov:Dec";
    n=split(m, mm, /:/); for (i=1; i<=n; i++) month[mm[i]]=i; }
    { for (k in pat) if ($9 ~ pat[k]) { printf("%s: %04i%02i%02i%02i%02i\n", pattern,
        substr($0, 21, 4), month[substr($0, 5, 3)], 0+substr($0, 9, 2),
        substr($0, 12,2), substr($0, 15, 2)); delete pat[k]; break }
    length(pat) == 0 { exit }'