使用getopts的Bash脚本-使用目录作为参数
好的,我有一个脚本,我用它来解析不同列和值的日志文件。我一直在尝试使用getopts来允许脚本对一个目录中的文件运行解析,并将输出保存到另一个目录。基本上,该命令是(应该是): 当前,如果脚本位于包含日志文件的目录中,它将 检查每个文件的前4个和后4个, 根据这些结果,以某种方式解析文件, 将修改输出到指定的输出目录, 继续下一个文件,完成 现在,如果我将脚本移到日志目录之外,我似乎无法让它对文件执行任何操作 下面是我的代码示例:使用getopts的Bash脚本-使用目录作为参数,bash,getopts,Bash,Getopts,好的,我有一个脚本,我用它来解析不同列和值的日志文件。我一直在尝试使用getopts来允许脚本对一个目录中的文件运行解析,并将输出保存到另一个目录。基本上,该命令是(应该是): 当前,如果脚本位于包含日志文件的目录中,它将 检查每个文件的前4个和后4个, 根据这些结果,以某种方式解析文件, 将修改输出到指定的输出目录, 继续下一个文件,完成 现在,如果我将脚本移到日志目录之外,我似乎无法让它对文件执行任何操作 下面是我的代码示例: #!/bin/bash while getopts ":i:o:
#!/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
#/bin/bash
而getopts“:i:o:”opt;做
案例$opt-in
(一)
indir=“$OPTARG”
;;
o)
outdir=“$OPTARG”
;;
\?)
回显“无效选项”
出口0
以撒
完成
班次$((可选ND-1))
对于*.log中的f
做
shopt-s nocasematch
f4l4=“${f:0:4}${f:${#f}-4}”
如果[[“${f4l4}”=“this.log”];然后
tr-cd“[:print:][\n”<$f|awk-f,'BEGIN{OFS=FS}for(i=6,i我认为问题在于:
f4l4="${f:0:4}${f:${#f}-4}"
如果f
包含路径,则您将从整个路径而不仅仅是文件名进行修剪,因此这永远不会是真的:
[[ "${f4l4}" = "this.log" ]]
这里有一个补丁,从*.log中的f的开始…
:
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)
对于$indir*.log##
indir=“$OPTARG”cd”$indir”…
?或者更好地在dir和file之间添加/
,即tr-cd”[:print:][\n”$indir/$f
?与$outdir/$f
相同。祝你好运。你建议在哪里插入它最好?在*.log
或之前代替f的并为f
子集?我现在不在机器上,所以我无法测试它以验证。明天我会让你知道。至于awk,我因为我知道awk不是问题所在。它不是我正在使用的实际awk:)澄清了放在哪里:)工作得很好!谢谢你的帮助,我的朋友!
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)