grep not working in a for loop over a list

5,164

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
Share:
5,164

Related videos on Youtube

Hussain Tamboli
Author by

Hussain Tamboli

About me Full Stack Developer at LAZADA Linkedin

Updated on September 18, 2022

Comments

  • Hussain Tamboli
    Hussain Tamboli almost 2 years

    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.

  • Hussain Tamboli
    Hussain Tamboli over 9 years
    Oh yes. My mistake! It works perfect now. Thanks a lot
  • terdon
    terdon over 9 years
    You're welcome, we posted essentially the same answer within seconds of each other so I thought I'd just combine them into yours and delete mine :). Welcome to the site!