Find the answer to your Linux question:
Results 1 to 3 of 3
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    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:

    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!!!

  2. #2
    Linux User
    Join Date
    Nov 2008
    Tokyo, Japan
    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:
    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.
    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.

    However, this can also work:
    # WARNING: This code is not safe from hackers.
    sed -e 's/[$]lec *\['\'type\'' *\] *= *'$A1' *;/$lec['\'type\''] = '$A2';/' \
        -e 's/[$]lec *\['\'media\'' *\] *= *array *("'$B1'") *;/$lec['\'media\''] = array("'$B2'")/' \
        input.file >output.file
    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.
    Last edited by ramin.honary; 03-29-2011 at 08:59 AM.

  3. #3
    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!

  4. $spacer_open

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts