LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   how to replace with variable using sed? (https://www.linuxquestions.org/questions/programming-9/how-to-replace-with-variable-using-sed-670571/)

babag 09-17-2008 12:19 PM

how to replace with variable using sed?
 
i have the following:
Code:

variable=$(sed -n '3p' truefalse.txt)

echo $variable

if [ "$variable" = "True" ] ; then
   
    sed -i '3 cFalse' truefalse.txt
else
   
    sed -i '3 cTrue' truefalse.txt
fi

variable=$(sed -n '3p' truefalse.txt)

echo $variable

this reads line three of a simple text file and
changes True to False or False to True depending
on what the line says.

how would i replace the '3' with a variable?
what is the syntax for that?

i tried a couple of things but was just guessing
and it didn't work.

thanks,
BabaG

w3bd3vil 09-17-2008 12:27 PM

Here is how you do that.
Quote:

bash-3.1# TEST=3
bash-3.1# export TEST
bash-3.1# cat test.txt
1
2
3
4
5
bash-3.1# sed -n $TEST'p' test.txt
3

jan61 09-17-2008 01:41 PM

Moin,

here's a simple example:
Code:

jan@jack:~/tmp/tf> cat data
True
False
False
True
True
True
False
jan@jack:~/tmp/tf> LINE=3
jan@jack:~/tmp/tf> sed "$LINE{s/True/_/;s/False/True/;s/_/False/}" data
True
False
True
True
True
True
False
jan@jack:~/tmp/tf> LINE=5
jan@jack:~/tmp/tf> sed "$LINE{s/True/_/;s/False/True/;s/_/False/}" data
True
False
False
True
False
True
False

If you want to use variables within a sed, you may not use '' around the sed script - no shell substitutions are done (this is a shell feature, not limited to sed). You must use "" instead or you place the variable outside the '' - for example:
Code:

sed 's/'"$VAR"'/something/' file
Jan

babag 09-17-2008 03:16 PM

thanks to you both! exactly what i was looking for.

BabaG

jschiwal 09-17-2008 03:28 PM

If a part of the sed command is provided by a variable, you need to be wary of whether the variable may contain a character such as a forward slash, which you would normally escape. If the variable contains a pathname for example, consider using another character such as "#" instead of a slash.

There is a trick you can try to test if the arguments are being passed as you believe. This may help with debugging.

set sed "$VAR"'s#'$var1'#old-'"$var1"'#p' file
echo $2

The arguments for set will be in $0, $1, etc. So you can echo them and see how the variable expansion went. The "sed" command will be in $1. The arguments to sed start with $2.


All times are GMT -5. The time now is 11:00 PM.