I have a file in which there is a line

byte address[] = { 0x54, 0x36, 0x45 };

I am trying to change the file by 3 command line parameters provided by the user -

grep byte | sed 's/\{.*\}/{ 0x$1, 0x$2, 0x$3 }/g' file.c

but no success.

The command used is -

sh script.sh 44 33 22

O/P -

byte address[] = { 0x44, 0x33, 0x22 };

Any help using sed/awk will be great!

  • show parameters values and desired result – RomanPerekhrest Jun 5 '17 at 18:50
  • @RomanPerekhrest please see the edit – Ashish K Jun 5 '17 at 18:52
  • variables should be enclosed with double quotes – RomanPerekhrest Jun 5 '17 at 18:57
  • 2
    You just have a typo. Change grep byte | to grep byte file.c | and remove the file.c argument you're giving to sed. – Mark Plotnick Jun 5 '17 at 19:16
  • 1
    Aside from the \{ \} that I didn't notice, I'm not sure why sed would be giving an error. Maybe the $1 $2 $3 had some whitespace in them. I should have recommended putting the arg to sed in double quotes instead of single quotes. Anyway, glad you got a solution for your problem. – Mark Plotnick Jun 5 '17 at 19:59

You need to realize that the \{ is special in sed. So you need this:

# filename: yourscript.sh
# usage: ./yourscript.sh 44 33 22
for arg; do set "$@" " 0x$arg"; shift; done
sed -e "/byte address\[\]/s/{[^}]*}/{$* }/"  yourfile.c


When invoked as:
%   ./yourscript.sh 44 33 22
byte address[] = { 0x44, 0x33, 0x22 };


  1. First task is to obtain the hexified numbers from the arguments. This we get by looping over the arguments list using the for loop. Each time, we append the hex-version of the current argument at the end of the arguments list $@ whilst at the same time taking away the current argument shift from the front of the list. So that means that at the end of the for loop iterations we would end up with the hexified arguments list.
  2. Now we set the IFS to a comma for joining the arguments with a comma.
  3. The sed code brings in the "$*" list inside the sed s/// replacement part.
  • Thankyou so much for your answer, actually the parameters are 16 in number and I was looking for some looping method to implement this. It's just that in byte address[] = { 0x54, 0x36, 0x45 }; the 0x54, 0x36, 0x45 is not fixed so couldn't use echo. – Ashish K Jun 5 '17 at 19:35
  • Just look at the sed code, it doesn't care how many hex are present in between the {...}. Just try the echo with your 16 hexes and give it a spin. – user218374 Jun 5 '17 at 19:38
  • Works a charm! :) A quick question, if you could tell me the significance of shift and $* here? – Ashish K Jun 5 '17 at 19:44
  • 1
    I've updated my answer, you may want to have a look. – user218374 Jun 5 '17 at 19:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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