-3

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
Ahmad Ismail
  • 11,636
  • 6
  • 52
  • 87
  • 2
    If you need a running index, you have to calculate it manually. Also, it is unclear what exactly you mean by _loop over output_. From the code snippets you posted, I infer that you mean to _loop over the individual words which a command writes to standard output_, but it's better to state this precisely when asking such a question. – user1934428 Aug 19 '22 at 06:08
  • This is what you already said. But the words "loop over output" does not have a real meaning. Should each iteration of the loop consume one character of the output, or one word of the output, or whatever? In your example, you are looping over the words in stdout of the command, and if this is really what you want to achieve in the general case, you better state this explicitly. – user1934428 Aug 19 '22 at 06:22
  • Neither the code you posted nor the text in your question says this. Furthermore, if you google for this problem, you will find many suggestions, so it's not clear to me at which point you are stuck. – user1934428 Aug 19 '22 at 06:48
  • 1
    Try the search term _stackoverflow bash read file by line_. – user1934428 Aug 19 '22 at 07:10

2 Answers2

0

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 .
0

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
Ahmad Ismail
  • 11,636
  • 6
  • 52
  • 87