简体   繁体   English

Shell脚本中的循环

[英]loops in shell script

i have two sets of data, say a=file1 file2 file3 and b=location1 location2 location3 . 我有两组数据,例如a=file1 file2 file3b=location1 location2 location3 Now i need to loop through and copy file1 to location1 , file2 to location2 and file3 to location3 . 现在我需要遍历和复制file1location1file2location2file3location3

If I use for loop, then after the first iteration of the the inner loop, it should go back to the outer loop, take the second value, go to the inner loop and take the second value and so on. 如果我使用for循环,则在内循环的第一次迭代之后,它应该返回外循环,获取第二个值,转到内循环并获取第二个值,依此类推。 Basically, the inner loop should not iterate for every value in the outer loop. 基本上,内部循环不应针对外部循环中的每个值进行迭代。

Is there a way to do this? 有没有办法做到这一点?

Thanks in advance. 提前致谢。 Sudhir 苏迪尔

It sounds like you're getting too complicated: 听起来您变得太复杂了:

a=(file1 file2 file3)
b=(location1 location2 location3)

for (( idx=0; idx<${#a[@]}; idx++ )); do
    cp -v "${a[idx]}" "${b[idx]}"
done

You can create bash arrays and make it work for you: 您可以创建bash数组并使其适合您:

declare -a f=( "file1" "file2" "file3" )
declare -a d=( "location1" "location2" "location3" )
c=0
for i in ${f[@]}; do
   echo $i ${d[$c]}
   ((c++))
done

Or without arrays something like this script should also work for you: 如果没有数组,则类似以下脚本的内容也应该适合您:

ci=0
for i in file1 file2 file3; do 
   ((ci++))
   cj=1
   for j in location1 location2 location3; do
      [[ $ci = $cj ]] && echo $i $j && break
     ((cj++))
   done
done

OUTPUT: 输出:

file1 location1
file2 location2
file3 location3

For sure $SHELL is simplest here, although once you start doing arrays with bash that advantage starts to dissipate ;-) So, just for comparison, here is a simple, non-oneliner perl approach: 可以肯定, $SHELL在这里是最简单的,尽管一旦您开始使用bash进行数组操作,优势就会消失;-)因此,为了进行比较,这是一种简单的,非单一的perl方法:

 #!/usr/bin/env perl
 my @arraya = qw/ file1 file2 file3/ ; 
 my @arrayb = qw/ location1 location2 location3/ ;
 foreach my $i ( 0 .. $#arraya ) {`cp $arraya[$i] $arrayb[$i]` }

@arraya and @arrayb can be constructed programmatically into very large lists with /m// matching and filtering, grep ing, find ing, etc. @arraya@arrayb可通过/m//匹配和过滤, grep ing, find等方式以编程方式构造成非常大的列表。

cf the perl based rename tool. 参见基于perlrename工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM