2014-02-21 4 views
0

Извините за плохое название, не стесняйтесь приспосабливать его к чему-то более подходящему.индексный массив: 1 до длины массива

Как я могу индексировать массивы с использованием zsh или bash скриптов, как я делаю для списков в R ниже;

# Some lists with the same number of elements 
list1 <- list(sample(letters,10)) 
list2 <- list(1:10) 

for(i in 1:length(list1)) { 
    a <- list1[[1]][i] 
    b <- list2[[1]][i] 
} 

print(paste(a,b)) # Or some other function where a and b are used simultaneously 

[1] "f 1" 
[1] "e 2" 
[1] "t 3" 
[1] "s 4" 
[1] "c 5" 
[1] "o 6" 
[1] "p 7" 
[1] "y 8" 
[1] "k 9" 
[1] "d 10" 

Код ниже, очевидно, только печатает последние элементы из обоих списков, так как я не нашел способ сделать 1 до длины массива

# dummy data 

echo 'A 1' > A.txt 
echo 'B 1' > B.txt 
echo 'C 1' > C.txt 

echo 'A,2' > A.csv 
echo 'B,2' > B.csv 
echo 'C,2' > C.csv 

txtlist=(*.txt) # create an array of .txt files 
csvlist=(*.csv) # create an array of .csv files 

# in zsh $#array returns the length of the array, so 

for i in $#txtlist; do 
    a=$txtlist[i] 
    b=$csvlist[i] 

    echo $a,$b # Or some other function where a and b are used simultaneously 

done 

#C.txt,C.csv 

Все указатели были бы очень оценил, спасибо!

ответ

4

bash и zsh оба знаем, что C-стиль для-петли:

От man 1 zshmisc (man 1 bash, по существу, то же самое):

for (([expr1] ; [expr2] ; [expr3])) do list done 
     The arithmetic expression expr1 is evaluated first (see the section `Arithmetic Evaluation'). The arithmetic expression expr2 is repeatedly 
     evaluated until it evaluates to zero and when non-zero, list is executed and the arithmetic expression expr3 evaluated. If any expression is 
     omitted, then it behaves as if it evaluated to 1. 

Пример zsh:

for ((i=1; i<=$#txtlist; i++)); do 
    echo "$txtlist[$i]" "$csvlist[$i]" 
done 

bash Пример:

for ((i=0; i<=${#txtlist[@]}; i++)); do 
    echo "${txtlist[$i]}" "${csvlist[$i]}" 
done 
+0

Спасибо за ответ, его именно то, что мне нужно. Не могли бы вы немного подробнее рассказать о синтаксисе zsh? –

2

Я не уверен, чтобы понять ваш пример, я извиняюсь, но вы можете сделать петлю, как, что в Баш:

myLength=${#myArray[@]} 
for ((i=1; i<${myLength}; i++)); 
do 
    echo ${myArray[$i]} 
done 
1

Используйте следующий синтаксис:

$ x=(1 2 3 4 5) 
$ print $x 
1 2 3 4 5 
$ print ${x:1} 
2 3 4 5 
Смежные вопросы