Skip to content
Advertisement

for loop syntax with grep in bash

I want to do text processing for lines in file.txt that ends with 0, I wrote an easy form of it to ask my question clearly.

$ cat file.txt
1 343 4352 0
324 4324 4324 324
432 432 2345 0

$ cat script.sh
for i in `grep " 0$" file.txt`
do
  echo $i; 
done

I want the output to be:

1 343 4352 0

432 432 2345 0

I want $i variable to be “1 343 4352 0” and after that to be “432 432 2345 0” but in this script $i variable is valued 1 then 343

Advertisement

Answer

You can do this:

IFS=$'n' arr=($(grep ' 0$' file.txt))
for  i in "${arr[@]}"
do
  echo "$i"
  #do other tasks here.
done
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement