Pipe grep to less with color

You need to use the grep –color=always option with less -R

Eg:

#grep -inr 'robots' * --color=always | less -R

 


You are reading this post on Joel G Mathew’s tech blog. Joel's personal blog is the Eyrie, hosted here.

Parse text files with assignments, and get the value – Bash

Suppose you have a text file containing the following:

strings=hello world

and you wanted to use the value of strings, which is “hello world” in your script

You can parse it with the following:

grep '^strings=' test | sed 's/strings=//g'

So the generic format is:

grep '^variablename=' filename | sed 's/variablename=//g'

The grep searches for a string beginning with ‘strings=’, in the file ‘test’, and outputs the following:

$grep '^strings=' test
strings=hello world

Next we have to remove the initial assignment part upto and including the ‘=’ sign, this is done by piping the output of grep, to sed.

Now the sed line substitutes the string “strings=” with an empty string. The substitution is done globally. Finally sed outputs just the value of the assigned variable.

Practical example:

I wanted to use the main User directory on the server, to make my backups more generic. I know that the file /etc/imscp/imscp.conf contains the following line:

USER_HOME_DIR = /var/www/virtual

So what I want is to get /var/www/virtual from this file, removing the assignment and spaces.

The solution is:

grep -i 'USER_HOME_DIR' imscp/imscp.conf | sed 's/USER_HOME_DIR[ ]=[ ]//'

which outputs:

/var/www/virtual

without the initial spaces. A space within a square brackets matches any number of spaces in the expression.

However, if you want to use these values in variables, you need to make minor adjustments to take care of variable escaping:

apache_home_var="USER_HOME_DIR"
apache_conf_file=/etc/imscp/imscp.conf
grep -i "$apache_home_var" "$apache_conf_file" | sed 's/'$apache_home_var'[ ]=[ ]//'

 


You are reading this post on Joel G Mathew’s tech blog. Joel's personal blog is the Eyrie, hosted here.

Setting default grep options

I find myself using grep with

grep -i -n –color ‘string’ filename

most of the time. As you know, -i is for Ignore case, and -n for Number line, and –color colorizes the output.

An extremely useful thing to have is to set the environment variable

export GREP_OPTIONS="--color -i -n"

So I just need to type:

grep 'string' filename

and the output is already colorized, and has line number and case ignored.

Read more.


You are reading this post on Joel G Mathew’s tech blog. Joel's personal blog is the Eyrie, hosted here.