输入文件中的循环脚本

时间:2018-07-02 14:59:26

标签: bash awk grep

我有一个参考文件,其中包含设备名称。例如WABEL8499IPM101。我正在使用此脚本设置基本名称(不包含最后3位数字)以查看参考文件并查看已使用的内容。如果使用101,则如果我总共请求2个文件,它将为我创建文件102和103。我希望使用一个输入文件来多次运行它。我还试图找出在搜索参考文件时找不到名称的情况下从101开始的方法。

我想使用输入文件来循环此操作,而不是每次都手动输入bash test.sh WABEL8499IPM 2。我希望能够构建一个需要比较然后输出的所有名称的输入文件。如果没有匹配项,它将开始在WABEL8499IPM101而不是仅在WABEL8499IPM1上创建名称。

输入文件示例:

ColumnA (BASE NAME)  ColumnB (QUANTITY)
WABEL8499IPM         2

脚本:

SRCFILE="~/Desktop/deviceinfo.csv"  
LOGDIR="~/Desktop/"  
LOGFILE="$LOGDIR/DeviceNames.csv"  

# base name, such as "WABEL8499IPM"
device_name=$1
# quantity, such as "2"
quantityNum=$2

# the largest in sequence, such as "WABEL8499IPM108"
max_sequence_name=$(cat $SRCFILE | grep -o -e "$device_name[0-9]*" | sort --reverse | head -n 1)

# extract the last 3digit number (such as "108") from max_sequence_name
max_sequence_num=$(echo $max_sequence_name | rev | cut -c 1-3 | rev)

# create new sequence_name
# such as ["WABEL8499IPM109", "WABEL8499IPM110"]
array_new_sequence_name=()
for i in $(seq 1 $quantityNum);
do
cnum=$((max_sequence_num + i))
array_new_sequence_name+=($(echo $device_name$cnum))
done

#CODE FOR CREATING OUTPUT FILE HERE
#for fn in ${array_new_sequence_name[@]}; do touch $fn; done;

# write log
for sqn in ${array_new_sequence_name[@]};
 do
echo $sqn >> $LOGFILE
done

用法:

bash test.sh WABEL8499IPM 2

日志文件中的结果:

WABEL8499IPM109
WABEL8499IPM110

1 个答案:

答案 0 :(得分:0)

只需在代码周围环绕一个循环,而不是假设args出现在命令行中。

SRCFILE="~/Desktop/deviceinfo.csv"  
LOGDIR="~/Desktop/"  
LOGFILE="$LOGDIR/DeviceNames.csv"  

while read device_name quantityNum
do max_sequence_name=$( grep -o -e "$device_name[0-9]*" $SRCFILE |
                        sort --reverse | head -n 1)
   max_sequence_num=${max_sequence_name: -3}

   array_new_sequence_name=()
   for i in $(seq 1 $quantityNum)
   do cnum=$((max_sequence_num + i))
      array_new_sequence_name+=("$device_name$cnum")
   done

   for sqn in ${array_new_sequence_name[@]};
   do echo $sqn >> $LOGFILE
   done
done < input.file

我现在可能会将输入文件作为参数传递。