1

My file data Pattern is below and i need output as 6 or 3 or 8 or 4 based on the variable value which is eth0 and eth1

eth0RX:6:eth0TX:3|eth1RX:8:eth1TX:4|

Below code works well

sed 's/.*eth0RX:\([0-9]\+\).*/\1/g' $EMSTATE/packetdrop.txt

But fails when I use dynamic variable like below

rxfile=sed 's/.*$iRX:\([0-9]\+\).*/\1/g' $EMSTATE/packetdrop.txt
2
  1. Inside single quotes, everything is what it is.  $i is a dollar sign followed by an i.  If you want to use a variable, you have to put the string into double quotes, somewhat like this:
    "s/.*$iRX:\([0-9]\+\).*/\1/g"
  2. But that won’t work, because it will look for a variable called iRX.  The simplest way to fix that is to put the variable name in braces, like this:
    "s/.*${i}RX:\([0-9]\+\).*/\1/g"
  3. You should put $EMSTATE into double quotes, too.  You can use "$EMSTATE"/packetdrop.txt or "$EMSTATE/packetdrop.txt", whichever you prefer.
  • Yes, there is a significant overlap.   (My answer is not the same as yours, or a subset, as you didn’t mention my point #3.)   But, more importantly, I started typing my answer before you posted yours.  And I believe that my explanation is somewhat clearer than yours. – Scott Oct 2 '17 at 6:16
2

Variable expansion doesn't happen in single quoting. Use double quote instead. And if you want to set result to a variable, you need to run sed within command substitution syntax $(...) and better to quote this as well "$(...)". Plus as $iRX can be a valid variable name better do ${i}.

rxfile="$(sed "s/.*${i}RX:\([0-9]\+\).*/\1/g" "$EMSTATE/packetdrop.txt" )"

Not the answer you're looking for? Browse other questions tagged or ask your own question.