Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 如何在shell脚本中使用2个数组执行for循环?_Bash_Shell - Fatal编程技术网

Bash 如何在shell脚本中使用2个数组执行for循环?

Bash 如何在shell脚本中使用2个数组执行for循环?,bash,shell,Bash,Shell,我必须首先声明两个数组,这两个数组也需要帮助 最初,它是两个单变量 day=$(hadoop fs -ls -R /user/hive/* | awk '/filename.txt.gz/' | tail -1 | date -d $(echo `awk '{print $6}'`) '+%b %-d' | tr -d ' ') time_stamp=$(hadoop fs -ls -R /user/hive/* |

我必须首先声明两个数组,这两个数组也需要帮助

最初,它是两个单变量

day=$(hadoop fs -ls -R /user/hive/* | 
        awk '/filename.txt.gz/' |
        tail -1 | 
        date -d $(echo `awk '{print $6}'`) '+%b %-d' | 
        tr -d ' ')

time_stamp=$(hadoop fs -ls -R /user/hive/* | 
             awk '/filename.txt.gz/' |
             tail -1 | 
             awk '{ print $7 }')
现在,我需要的不是
tail-1
,而是
tail-5
。那么首先,我如何制作这两个数组


第二个问题,如何使用
$day
$time\u stamp
的成对值中的每个值为
创建一个
循环?我不能使用array\u combine,因为我需要分别对每个数组执行操作。谢谢

您正在将数据收集到字符串中,而不是数组中。但除此之外,您的代码可能需要进行显著的重构——根据一般经验,如果在Awk中发生了某些事情,其余大部分也应该在Awk中发生

使用
variable=(数组的值)
分配给数组,要从子流程获取值,它是
variable=($(生成值的命令))

这里是重构代码的第一次尝试

# Avoid repeated code -- break this out into a function
extract_field () {
    hadoop fs -ls -R /user/hive/* | 
    # Get rid of the tail and the repeated Awk
    # Notice backslashes in regex
    # Pass in the field to extract as a parameter
    awk -v field="$1" '/filename\.txt\.gz/ { d[++i]=$field }
        END { for(j=i-5; j<=i; ++j) print d[j] }'
)

day=($(extract_field 6 |
    # Refactor accordingly
    # And if you don't want a space in the format string, don't put a space in the format string in the first place
    xargs -i {} date -d {} '+%b%-d'))

time_stamp=($(extract_field 7))
#避免重复代码--将其分解为函数
提取_字段(){
hadoop fs-ls-R/user/hive/*|
#摆脱尾巴和重复的Awk
#注意正则表达式中的反斜杠
#作为参数传入要提取的字段
awk-v field=“$1””/filename\.txt\.gz/{d[++i]=$field}

END{for(j=i-5;j首先去掉
“=”
周围的空格,然后
day=($(…)
将创建一个索引数组
day
。与
time\u stamp=($(…)
相同。注意:这适用于高级shell,如bash,POSIX shell中没有数组(因此,您应该使用您正在使用的实际shell重新标记您的问题——因为它肯定不是POSIX shell),然后您将通过索引对数组进行迭代。假设bash:
for((i=0;i<${day[@]};i++);do echo“${day[i]}->${timestamp[i]}”;done
作为一个备用函数,Awk数组从与正则表达式匹配的行中收集所有值。如果来自
hadoop ls
的输出可能很大,那么在处理输入时,可以考虑只保留内存中列表中的最后n项。
combined=($(hadoop fs -ls -R /user/hive/* | 
    awk '/filename\.txt\.gz/ { d[++i]=$6 " " $7 }
        END { for(j=i-5; j<=i; ++j) print d[j] }'))
for ((i=0; i<"${#combined[@]}"; ++i)); do
    day[$i]="$(date -d "${combined[i]% *}" +'%b%-d')"
    time_stamp[$i]="${combined[i]#* }"
done
unset combined