Results 1 to 5 of 5
I have hit this problem several times and am tired of crappy workarounds... I need to pass a variable to sed. Supposedly using soft quotes will work, but it doesn't ...
- 07-10-2009 #1
Pass Variables to sed
I have hit this problem several times and am tired of crappy workarounds... I need to pass a variable to sed. Supposedly using soft quotes will work, but it doesn't when I am doing command substitution, and I have never successfully done it:
where $LINO stores the current line number and $1 the file being worked on.Code:LINE=`sed -n "$LINOp $1"`
Even though I would like this problem to be solved, I'd also be interested in a better way to print a specific line from a file... in order to keep working on my script I am forced to change the above to:
Which is ugly and inelegant....Code:LINE=`cat -n $1 | grep "^ *$LINO" | cut -d " " -f 2`
- 07-11-2009 #2Linux User
- Join Date
- May 2008
- Location
- NYC, moved from KS & MO
- Posts
- 251
Try this example that I have tested and I hope you will get the idea how to use it in your case:
ex1.sh
dataCode:#!/bin/bash old=this new=that file=$1 sedcmd="sed 's/$old/$new/g' $file" eval $sedcmd
When you runCode:what's this?
You should be able to seeCode:bash ex1.sh data
Code:what's that?
- 07-11-2009 #3Linux User
- Join Date
- May 2008
- Location
- NYC, moved from KS & MO
- Posts
- 251
Trywhere $LINO stores the current line number and $1 the file being worked on.Code:LINE=`sed -n "$LINOp $1"`
instead.Code:LINE=`sed -n "${LINO}p" $1`
As for the better way to read a specific line in a file, I think the sed method you were trying to use is already pretty simple and efficient.
- 07-11-2009 #4
@secondmouse: Thanks for the help, this has been a barrier for me for a long time; now I can finally write some of the scripts I had to scrap. It is quite interesting to let bash do the variable substitution into another variable before we actually execute sed.
As for the command substitution, what is the difference between $(), ${}, and ``?
EDIT: Nevermind, I see that $() fork a subshell and as such disallows parameter expansion; things are taken literally, whereas `` allows special characters to be parsed. ${} serves to separate the variable from other characters (which tells me why $LINOp didn't work, duh...).
- 07-12-2009 #5Linux User
- Join Date
- May 2008
- Location
- NYC, moved from KS & MO
- Posts
- 251
Glad it helps.


Reply With Quote