using a variable in a sed statement

Posted on 2011-05-05
Last Modified: 2012-05-11
I can't get this sed statement to work. Trying to use a variable. Any ideas?

cp /etc/shadow /etc/shadow.bak

OPASSWD=`grep ttc_root /etc/shadow.bak | awk -F: '{print $2}'`

(OPASSWD is the encrypted password, and may contain metacharacters)

sed -e 's/$OPASSWD/spoo/' /etc/shadow.bak

Question by:sonriks
    LVL 45

    Expert Comment

    Use double quotes instead of single quotes.  :)

      sed -e "s/$OPASSWD/spoo/" /etc/shadow.bak

    LVL 1

    Author Comment

    Thanks, Kent .. that worked like a charm for a "plain" string.

    I need this to work for variables that contains metacharacters, as many entries in the shadow file do, characters like "/", "\", "$". etc.


    Is there some way that the string with metachars being taken as a literal?

    LVL 45

    Accepted Solution

    There is an issue when the substituted value contains the same character that you're using as a delimiter.  The command:

      sed -e "s/$OPASSWD/spoo/" /etc/shadow.bak

    literally becomes:

      sed -e "s/U/gx5Pid8Ykmk/spoo/" /etc/shadow.bak

    after the substitution, giving an "extra parameter" to the *s* function.

    You can use a lot of characters for the delimiter.  Can you pick one that won't occur in the data?
    LVL 1

    Author Closing Comment

    Thanks. I used a ":" as the delimiter and it worked fine!

    Featured Post

    6 Surprising Benefits of Threat Intelligence

    All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

    Join & Write a Comment

    Installing FreeBSD… FreeBSD is a darling of an operating system. The stability and usability make it a clear choice for servers and desktops (for the cunning). Savvy?  The Ports collection makes available every popular FOSS application and packag…
    Java performance on Solaris - Managing CPUs There are various resource controls in operating system which directly/indirectly influence the performance of application. one of the most important resource controls is "CPU".   In a multithreaded…
    Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
    This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now