grep not working in a for loop over a list Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of grep not working in a for loop over a list without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have some log files. And I have a list of user ids. My log files are in a particular format

log-yyyy-mm-dd
e.g. log-2014-09-30

I am trying to search each userId in the log file. This is what I am doing –

for userid in 234, 283, 893, 982, 323; do cat log-2014-09-30 | grep -a "user deleted "$userid  | tail -1; done

Ideally it should search each user id in the file and print the last match. I will then search in log-2014-09-29 for the remaining user ids and so on.

But it is only printing the match for the last user id.

INFO - 2014-09-30 22:49:00 - user deleted 323

What am I doing wrong? please help me out.

Answer

Get rid of the commas in the userid list. The way to pass a list to a for loop is to give it space separated values, not comma separated:

for userid in 234, 283, 893, 982, 323; do echo "$userid";done

prints

234,
283,
893,
982,
323

But

for userid in 234 283 893 982 323; do echo "$userid";done

prints

234
283
893
982
323

So, you should do

for userid in 234 283 893 982 323; do 
    grep -a "user deleted $userid" log-2014-09-30  | tail -n 1
done
We are here to answer your question about grep not working in a for loop over a list - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji