Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

shell - Unix bash script grep loop counter (for)

I am looping our the a grep result. The result contains 10 lines (every line has different content). So the loop stuff in the loop gets executed 10 times.

I need to get the index, 0-9, in the run so i can do actions based on the index.

ABC=(cat test.log | grep "stuff")

counter=0
for x in $ABC
do
        echo $x      
        ((counter++))
        echo "COUNTER $counter"
done

Currently the counter won't really change.

Output:

51209
120049
148480
1211441
373948
0
0
0
728304
0
COUNTER: 1
question from:https://stackoverflow.com/questions/65624106/unix-bash-script-grep-loop-counter-for

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your shell script contains what should be an obvious syntax error.

ABC=(cat test.log | grep "stuff")

This fails with

-bash: syntax error near unexpected token `|'

There is no need to save the output in a variable if you only want to process one at a time (and obviously no need for the useless cat).

grep "stuff" test.log | nl

gets you numbered lines, though the index will be 1-based, not zero-based.

If you absolutely need zero-based, refactoring to Awk should solve it easily:

awk '/stuff/ { print n++, $0 }' test.log

If you want to loop over this and do something more with this information,

awk '/stuff/ { print n++, $0 }' test.log |
while read -r index output; do
    echo index is "$index"
    echo output is "$output"
done

Because the while loop executes in a subshell the value of index will not be visible outside of the loop. (I guess that's what your real code did with the counter as well. I don't think that part of the code you posted will repro either.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...