Home > Software design >  How to use ANSI-C Quoting with Shell variables?
How to use ANSI-C Quoting with Shell variables?

Time:10-20

I have a sed command with hex replacement, which i used in Busybox: ( BusyBox v1.32.1 (2022-03-05 22:56:19 CET) multi-call binary.)

This works on other Linux environments:

HEXCODE=34
sed "s/\xa1\xb2/\x12\x$HEXCODE/g" < file.bin > file2.bin

On my busybox sed environment it doesn't.

This works fine with Ansi Encoding string:

This works:

sed $'s/\xa1\xb2/\x12\x34/g' < file.bin > file2.bin

But i want this here with Shell variable use:

HEXCODE=34
sed $'s/\xa1\xb2/\x12\x$HEXCODE/g' < file.bin > file2.bin

This doen't work for me, so can I get some help here?

Edit:

pynexj's tipps helps here with eval / printf: Just need this oneliner here:

But i want this here with Shell variable use:

HEXCODE=34
eval sed "\$'s/\xa1\xb2/\x12\x$HEXCODE/g'" < file.bin > file2.bin

CodePudding user response:

You can use printf or eval. See the following example:

[bash-5.1] $ cat foo.sh
s='hello world'

HEX=4c  # 'L'

# use `printf'
cmd=$( printf "s/l/\x$HEX/g" )
echo "$s" | busybox sed -e "$cmd"

# use `eval'
eval cmd="\$'s/l/\x$HEX/g' "
echo "$s" | busybox sed -e "$cmd"
[bash-5.1] $ busybox sh foo.sh
heLLo worLd
heLLo worLd
  • Related