Sed Question

Home » CentOS » Sed Question
CentOS 6 Comments

I am trying to use sed to change a value in a pipe.

——————- This is the two line script CHANGE=”1234″

cat my_file.txt | sed ‘s/CANCELID/$CHANGE/’ > cancel.txt
—————–

6 thoughts on - Sed Question

  • sed doesn’t perform environment variable expansion. That is to say that when you instruct sed to substitute “$CHANGE” for “CANCELID”, “$CHANGE”
    is a literal string that will be substituted.

    bash, on the other hand, does perform environment variable expansion for strings not enclosed in single quotes. So, you probably meant:
    cat my_file.txt | sed “s/CANCELID/$CHANGE/” > cancel.txt

    In that case, bash will replace $CHANGE with 1234 before starting sed with that argument.

    Additionally, you can avoid using “cat” to make the script more efficient. You’ll start fewer processes, and complete more quickly.
    cat is almost never needed unless you actually need to con”cat”enate multiple files.

    A couple of other changes I’d suggest as better scripting style: Enclose your variable names in ${} to avoid abiguity, and use lower case variable names except when you have a variable that you mean to export, and upper case only exported variables.

    sed “s/CANCELID/${change}/” < my_file.txt > cancel.txt

  • I sometimes like to use cat purely for stylistic reasons :

    cat file.txt |\
    sed -e s?”foo”?”bar”?g |\
    sed -e s?”dirty”?”clean?” |\
    > file2.txt

    It lets me line up my sed expressions.

    But yes, that is wasting a process for easier visualization. Worth it to me.

  • I don’t understand why you’d quote that way. Though unlikely, you could potentially match a filename in the working directory, and hose the sed command. For efficiency’s sake, you can eliminate cat and one of the two sed processes, and still have a more readable command:

    sed -e ‘s?foo?bar?g’ \
    -e ‘s?dirty?clean?’ \
    < file.txt > file2.txt