Home > Blockchain >  loop over output of command and print both index and value
loop over output of command and print both index and value

Time:08-19

I have checked Looping over arrays, printing both index and value. The issue is I want to loop over output of command and not an array.

The code i came up with is:

array=($(seq 1 10))

for i in "${!array[@]}"; do
  printf "%s\t%s\n" "$i" "${array[$i]}"
done

or,

ITER=0
for I in $(seq 1 10)
do  
    echo ${I} ${ITER}
    ITER=$(expr $ITER   1)
done

What i want to know is, is it possible to do it within the loop only (without array or ITER) outside the loop?

What i am looking for is something like:

for index,value in $(seq 1 10); do
  echo $index $value
done

CodePudding user response:

Let us know your actual requirement:

01)
#!/bin/bash
index=0
for filename in $(ls -atr)
do
        indx=$(($indx 1))
        echo "Index: $indx $filename"
done

output:

$  ./73412398.sh
Index: 1 ..
Index: 2 73412398.sh
Index: 3 .

One more try:

for index in $(ls -atr | grep -n $)
do
 echo $index | sed "s/\([0-9]*\):/\1 /;"
done

output:

1 ..
2 73412398.sh
3 .

CodePudding user response:

after modifying murugesan openssl's answer, the solution for me is:

for indexval in $(ls -atr | grep -n $)
do
 echo index is "${indexval%%:*}"
 echo value is "${indexval#*:}"
done
  •  Tags:  
  • bash
  • Related