【问题标题】:Create Array of File paths with a loop and grep through them使用循环创建文件路径数组并通过它们 grep
【发布时间】:2019-02-16 13:33:48
【问题描述】:

我想将每个输出文件路径保存到一个变量中,然后通过 grep 查找时间戳。我想通过从我正在循环的节点列表中添加 nodeId 来标记每个变量。当我使用以下代码尝试此操作时,出现错误

output1_1:找不到命令

nodeList=('1_1' '1_6' '2_1' '2_6')
for i in "${nodeList[@]}"
do
   output${i}=$CWD/output/abc${i}.txt
   times${i}=$(grep  -m 1 '\"path\":' $output${i}| sed 's/.*timestampUtc\"://g' | sed 's/,.*//g')
done

【问题讨论】:

  • 为什么不使用关联数组? declare -A output times,然后是output[$i]=...
  • 代替grep -m | sed | sed,试试这个(多合一)sed 命令:sed '/\"path\":/{s/.*timestampUtc\":/\([^,]*\),.*/\1/;q};d'

标签: arrays string bash file loops


【解决方案1】:

按照@muru的建议,试试

declare -A output times
nodeList=('1_1' '1_6' '2_1' '2_6')
for i in "${nodeList[@]}"; do
   output[${i}]=${PWD}/output/abc${i}.txt
   times[${i}]=$(grep  -m 1 '\"path\":' ${output[${i}]} | sed 's/.*timestampUtc\"://g' | sed 's/,.*//g')
done

【讨论】:

【解决方案2】:

设置名称派生自另一个变量的变量的一种方法是使用-v 选项'printf'。 要获取名称在另一个变量中的变量的值(例如 varname),请使用 ${!varname}

请参阅 Creating a string variable name from the value of another stringHow can I generate new variable names on the fly in a shell script?

使用这些可能的循环体是:

output_var=output${i}
times_var=times${i}

printf -v "$output_var" '%s' "$CWD/output/abc${i}.txt"
printf -v "$times_var" '%s' "$(grep  -m 1 '\"path\":' "${!output_var}" | sed 's/.*timestampUtc\"://g' | sed 's/,.*//g')"

请注意(除非CWD 在您的程序中的其他位置设置)您可能需要$PWD 而不是$CWD

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    相关资源
    最近更新 更多