1

I am new to shell scripting and having trouble doing following:

I have this:

MY_MACR0_VALUE="123ABCD"

I want to convert it to this:

#define MY_MACR0_VALUE "123ABCD"

I am doing this:

//that string is coming from command line 

    newvar=$(echo "$1" | tr '=' ' ') 

    echo "#define $newvar" >> MacroFile.h

I am getting this:

#define MY_MACR0_VALUE 123ABCD

instead of

#define MY_MACR0_VALUE "123ABCD"

The double quotes are missing.

How can I fix my script to get the desired result?

EDIT

I may also have some non valued Macros from the commandline , like

INCLUDE_SOMETHING

which should be changed to

#define INCLUDE_SOMETHING

So I dont need to change anything in them.

4 Answers 4

2

The problem is, shell is stripping out the quotes so the script does not even see them. You can use your script if you escape the quotes in the argument:

sh script.sh MY_MACR0_VALUE=\"123ABCD\"

Or you can use this line in the script:

echo "#define $(sed '/=/{s/=/ "/;s/$/"/}' <<< $1)" >> MacroFile.h
Sign up to request clarification or add additional context in comments.

1 Comment

It fixed the issue for #define MY_MACR0_VALUE "123ABCD" but i have some Macros to be passed in the commandline which wont have any value for eg: #define INCLUDE_SOMEFILE , your solution is corrupting them by adding an extra " at their end like this #define INCLUDE_SOMEFILE". My bad I missed to mention it in question.
0

You can use sed. Like this:

sed 's/\([^=]*\)=\(.*\)/#define \1 \2/' <<< "$1"

Output:

#define MY_MACR0_VALUE "123ABCD"    

The command obtains the part before and after the = into separate capturing groups and populates them to the final string.

Comments

0

sed solution without using capturing groups,

sed 's/^/#define /g;s/=/ /g' <<< "$1"

Example:

$ echo 'MY_MACR0_VALUE="123ABCD"' | sed 's/^/#define /g;s/=/ /g'
#define MY_MACR0_VALUE "123ABCD"

Explanation:

  • s/^/#define /g Adds #define at the starting.

  • s/=/ / Replaces = sign with space.

Comments

0

awk -F "=" '{print "#define",$1,$2}' <<< "$1"

Field separator is no shown so it removed the = and prints the first and second part with #define before them

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.