# Grep results to store in a shell variable

**URL:** <https://community.unix.com/t/grep-results-to-store-in-a-shell-variable/173562>\
**Category:** Shell Programming and Scripting\
**Created:** [July 26, 2007, 11:39am UTC](https://community.unix.com/t/grep-results-to-store-in-a-shell-variable/173562 "2007-07-26T11:39:27Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![jojan](https://community.unix.com/letter_avatar/jojan/32/6_22734026db12803ebb3e059622ac3534.png) [@jojan](https://community.unix.com/u/jojan)\
**Post date:** [July 26, 2007, 11:39am UTC](https://community.unix.com/t/grep-results-to-store-in-a-shell-variable/173562/1 "2007-07-26T11:39:27Z")

</div>

I have the results of a grep with -n store in a shell variable  
ie  
VAR=`grep -n -e 'PATTERN' file`  
How ever I am missing the line breaks in the variable , How do I store the resualts of grep with many lines in to a variables. I want the varable should be the sawmway as we do the grep

grep -n -e 'PATTERN' file`

shoeld be the same way as that of

var=`grep -n -e 'PATTERN' file`  
echo $var

I need the $var for further processing

---

<div class="post-metadata">

**Author:** ![Shell\_Life](https://community.unix.com/user_avatar/community.unix.com/shell_life/32/521_2.png) [@Shell\_Life](https://community.unix.com/u/Shell_Life)\
**Post date:** [July 26, 2007, 11:43am UTC](https://community.unix.com/t/grep-results-to-store-in-a-shell-variable/173562/2 "2007-07-26T11:43:49Z")

</div>

```nohighlight
for mLine in `grep -n 'PATTERN' file`
do
  echo 'mLine = '${mLine}
done

```

---

<div class="post-metadata">

**Author:** ![jojan](https://community.unix.com/letter_avatar/jojan/32/6_22734026db12803ebb3e059622ac3534.png) [@jojan](https://community.unix.com/u/jojan)\
**Post date:** [July 26, 2007, 12:40pm UTC](https://community.unix.com/t/grep-results-to-store-in-a-shell-variable/173562/3 "2007-07-26T12:40:00Z")

</div>

fanstastic it worked ! My file is very large , so I do not want to grep it again and again! Instead do s single grep and store all insatnces together  
Thanks

---

<div class="post-metadata">

**Author:** ![Franklin52](https://community.unix.com/user_avatar/community.unix.com/franklin52/32/500_2.png) [@Franklin52](https://community.unix.com/u/Franklin52)\
**Post date:** [July 26, 2007, 12:44pm UTC](https://community.unix.com/t/grep-results-to-store-in-a-shell-variable/173562/4 "2007-07-26T12:44:40Z")

</div>

If you want to keep the value in a variable seperated by a new line you can do something like this:

```nohighlight
OLDIFS=$IFS
IFS='\n'

var=`grep -n -e 'PATTERN' file`
echo $var

IFS=$OLDIFS

```

Regards
