0

I want to write the result of grep inside for loop into a file, keeping original file structure. Original file:

$cat newtest1
some_text
/homes/myself/joz
ivan petrov - 20/10/19
new customer:
/homes/myself/silvia
john smith - 30/11/19
old customer:
some_text

I am using grep in for loop and getting the following:

$for i in `cat newtest1 | grep customer -B2`; do echo $i; done
/homes/myself/joz
ivan
petrov
-

etc. File's structure got changed. I tried printf - the same result. Question: how to keep file's structure using grep in for loop?

Josef Klimuk
  • 1,596

1 Answers1

3

You need to quote variables and the result of command substitution to prevent word splitting:

for i in "$(<newtest1 grep customer -B2)"; do
  echo "$i"
done

Of course to just output the matching lines you don’t need the for loop, but I suppose you want to do other things with the lines. In any case you don’t need the cat, you can let grep open the file with grep … newtest1 or let the shell open it and assign its content to grep’s stdin as I did above. The latter has a number of advantages explained in this great answer: When should I use input redirection?

dessert
  • 39,982