Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I came across various examples on printing next line after a match, that use awk and sed. I'm using it in my code and it works fine. Now I want to use a variable instead of a hardcoded value for the pattern match. The search pattern string includes forward slashes "/". How do I use a variable that has "/" in it and use it to print the next line after the match? The following doesn't seem to work:

 var="/somePath/to/my/home"  
 val=`echo -e "$someStr" | sed -n ':$var:{n;p;}'`

In this case, val is always blank. I'm using using ":" as the delimiter instead of "/". I'm on a Mac OS X.

share|improve this question
add comment

2 Answers

up vote 0 down vote accepted

Change your sed command as follows:

sed -n "\:$var: {n;p;}"

Two points:

  1. The best you could have hoped for with your version is to search for “$var”. To search for “/somePath/to/my/home”, you must replace your single quotes (') with double quotes (") to allow “$var” to be replaced by “/somePath/to/my/home”.

  2. In sed, a delimited regular expression can look like

/     regular_expression     /

or

\other_delimiter   regular_expression   other_delimiter(repeated)

so you need the \ before the :.

share|improve this answer
add comment

While setting the variable "var", escape the backslashes:

var="\/somePath\/to\/my\/home"
sed -n "/$var/{n;p;}" file
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.