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?

4
  • What's your intent with the for loop? Why not just the grep?
    – egmont
    Mar 12, 2019 at 8:58
  • For I want to use some ifs inside for loop. Mar 12, 2019 at 9:06
  • This sounds like an XY problem - for example how to process 3-line records that are delimited by the string "customer:" Mar 12, 2019 at 12:00
  • The question was asked exactly about what I needed and the answer helped. It was meaningless for me to include if statements, since I had no question about if statements. Mar 12, 2019 at 13:15

1 Answer 1

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?

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .