gpt4 book ai didi

linux - 在 bash for 循环中调用当前项和下一项

转载 作者:太空狗 更新时间:2023-10-29 11:27:11 26 4
gpt4 key购买 nike

我正在进行反复分析,并且必须向大型计算机集群上的批处理系统提交 5000 多个作业。

我想运行一个 bash for 循环,但同时调用我的脚本中的当前列表项和下一项。我不确定使用这种格式执行此操作的最佳方法:

#! /bin/bash
for i in `cat list.txt`;
do
# run a bunch of code on $i (ex. Data file for 'Apples')
# compare input of $i with next in list {$i+1} (ex. Compare 'Apples' to 'Oranges', save output)
# take output of this comparison and use it as an input for the next analysis of $i (ex. analyze 'Apples' some more, save output for the next step, analyze data on 'Oranges')
# save this output as the input for next script which analyses the next item in the list {$i+1} (Analysis of 'Oranges' with input data from 'Apples', and comparing to 'Grapes' in the middle of the loop, etc., etc.)
done

在 while 循环中提供表格输入列表对我来说最简单吗?我真的不想这样做,因为我必须进行一些代码编辑,尽管是次要的。

感谢您对新手的帮助——我浏览了整个互联网并浏览了一堆书籍,但没有找到一个好的方法来做到这一点。

编辑:出于某种原因,我认为可能有一个 for 循环技巧可以做到这一点,但我想没有;使用表格输入进行 while 循环对我来说可能更容易。我准备这样做,但我不想重写我已有的代码。

更新:非常感谢大家的宝贵时间和意见!非常感谢。

最佳答案

另一种解决方案是使用 bash 数组。例如,给定一个文件 list.txt,内容为:

1
2
3
4
4
5

您可以创建一个以文件行作为元素的数组变量:

$ myarray=(1 2 3 4 4 5)

虽然您也可以执行 myarray=( $(echo list.txt) ) 这可能会在空格处拆分并不适本地处理其他输出,但更好的方法是:

$ IFS=$'\n' read -r -d '' -a myarray < list.txt

然后您可以访问元素:

$ echo "${myarray[2]}"
3

数组的长度由 ${#myarray[@]} 给出。 ${!myarray[@]} 给出了所有索引的列表,您可以遍历此索引列表:

for i in "${!myarray[@]}"; do 
echo "${myarray[$i]} ${myarray[$(( $i + 1))]}"
done

输出:

1 2
2 3
3 4
4 4
4 5
5

虽然对于您的特定用例可能有更简单的解决方案,但这将允许您在循环中访问数组元素的任意组合。

关于linux - 在 bash for 循环中调用当前项和下一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30462040/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com