Results 1 to 3 of 3
Hello all,
This is my first post, and I am new to linux (and scripting too). Could you help me to format a sed command please?
I have this two ...
- 03-28-2011 #1Just Joined!
- Join Date
- Mar 2011
- Posts
- 2
Could someone help me with sed?
Hello all,
This is my first post, and I am new to linux (and scripting too). Could you help me to format a sed command please?
I have this two lines in a file:
$lec['type'] = on;
$lec['media'] = array("");
I need to replace both with this lines
$lec['type'] = off;
$lec['media'] = array("ndp");
could you help me please? I tried a lot of combination without any success, my last try was:
peso="$"
v1="^"$peso"lec['type'] = on
v2=$peso"lec['type'] = off;"
sed -i s/$v1/$v2/ /x/x.php
Not working...
No idea for second line...
Thanks in advance!!!
- 03-29-2011 #2Linux Newbie
- Join Date
- Nov 2008
- Location
- Tokyo, Japan
- Posts
- 243
Sed is a pretty tricky tool to use. Sed uses "regular expressions" (read the manual "man -s 7 regex") rather than exact string matches.
To make "sed" do find/replace, you must use the syntax: "s/find-regex/replace-string/". In your case, this code will work:So you must also "sanitize" parameters to "sed" (use the "\" character to remove characters with special meanings). You should never simply pass variables on the command line to "sed", it will make your program a danger to security by way of a "code-injection attack", especially if those variables can be defined by other users of your program.Code:sed -e 's/[$]lec *\['\'type\'' *\] *= *on *;/$lec['\'type\''] = off;/' \ -e 's/[$]lec *\['\'media\'' *\] *= *array *("") *;/$lec['\'media\''] = array("ndp")/' \ input.file >output.file # WARNING: make sure "input.file" and "output.file" are DIFFERENT FILES # or else "input.file" will be deleted.
However, this can also work:So if you set $A1, $A2, or $B1, $B2 to use strings from the command line arguments, for example, A1=$1; A2=$2 or if those variables are set from standard input, for example A1=$(cat), your program could very easily be hacked to modify the contents of your input file to cause harm to your system.Code:# WARNING: This code is not safe from hackers. A1="on" A2="off" B1="" B2="ndp" sed -e 's/[$]lec *\['\'type\'' *\] *= *'$A1' *;/$lec['\'type\''] = '$A2';/' \ -e 's/[$]lec *\['\'media\'' *\] *= *array *("'$B1'") *;/$lec['\'media\''] = array("'$B2'")/' \ input.file >output.fileLast edited by ramin.honary; 03-29-2011 at 08:59 AM.
- 03-29-2011 #3Just Joined!
- Join Date
- Mar 2011
- Posts
- 2
Your explanation was very instructive, i didn't realice the vulnerability to hackers when using variables on scripts like this... thanks for the advice.
I will try tonight the script!, thank you very much!


Reply With Quote