2016-04-23 65 views
2

好的,所以我有一个脚本,我正在使用它来解析具有不同列和值的各种日志文件。我一直试图使用getopts来允许我的脚本对一个目录中的文件运行解析,并将输出保存到另一个目录。本质上,命令是(应该是):使用getopts的Bash脚本 - 使用目录作为参数

./script.sh -i /absolute/input/dir/ -o /absolute/output/dir/ 

目前,如果脚本是在目录中的日志文件,它会

检查第4和每个文件的最后4, 基于这些结果以某种方式解析文件, 输出修改到分配的输出目录, 移到下一个文件,完成。

现在,如果我将脚本移动到日志目录之外,我似乎无法让它对这些文件执行任何操作。

这里是我的代码示例:

#!/bin/bash 
while getopts ":i:o:" opt; do 
case $opt in 
    i) 
    indir="$OPTARG" 
    ;; 
    o) 
    outdir="$OPTARG" 
    ;; 
    \?) 
    echo "invalid option" 
    exit 0 
    esac 
done 
shift $((OPTIND-1)) 

for f in *.log 
do 
    shopt -s nocasematch 
    f4l4="${f:0:4}${f:${#f}-4}" 
    if [[ "${f4l4}" = "this.log" ]]; then 
    tr -cd "[:print:]\n" < $f | awk -F, 'BEGIN{OFS=FS}for(i=6,i<8;i++) $i=sprintf(%02X,$i)}1' > $outdir$f.csv 
    sed -i '1icolumn1,column2,column3,column4,5,6,7,8,etc' $outdir$f.csv 
    elif [[ "${f4l4}" = "that.log" ]]; then 
    parse log file another way < $f | sed this and that > $outdir$f.csv1 

    fi 
done 

所以我使用中的$indir变量声明($indir$f instead of $f)都试过,但没有奏效。如果我echo $f那么我可以看到目录中的所有文件,但脚本不会做任何事情。

总之,我想使用getopts指定一个输入目录,其中包含要编辑的文件以及要保存的编辑文件的输出目录。

想法?

+0

'下载= “$ OPTARG”; cd“$ indir”; ....'?或者更好的代码在目录和文件之间添加'/',即'tr -cd'[:print:] \ n“<$ indir/$ f'? '$ outdir/$ f'也一样。祝你好运。 – shellter

回答

1

我相信这个问题是这样的:

f4l4="${f:0:4}${f:${#f}-4}" 

如果f包括路径,然后你从整个路径修剪,不只是文件名,所以这是不正确的:

[[ "${f4l4}" = "this.log" ]] 

这里有一个修复,开始for f in *.log...

for p in $indir*.log ## <-- change "for f in *.log" to this 
do 
    f=`basename "$p"` ## <-- new 
    ... 
    if [[ "${f4l4}" = "this.log" ]]; then 
    tr -cd "[:print:]\n" < $p ## <-- change ($f to $p) 
    ... 
    elif [[ "${f4l4}" = "that.log" ]]; then 
    parse log file another way < $p ## <-- change ($f to $p) 
+0

你认为哪里最适合插入?代替'for f in * .log'或之前的子集'for f'?我现在不在机器上,我现在有了我的脚本,所以我无法测试它来验证。明天我会通知你。 至于awk,我只是把它放在了不稳定的地方,因为我知道awk不是问题。这不是我正在使用的实际awk :) – Fetch

+0

澄清在哪里:) – webb

+0

工作完美!感谢您的帮助,我的朋友! – Fetch