Is there a way to escape a variable call in powershell? - string

I am trying to use powershell to generate a build.include script for visual studio. They both use ${variable} as a way of referencing variables.
I was wondering if there is a way to escape that in a string.
E.g
$string = #'
This is a `${string} I want to escape and {0} one I do not want to
'# -f $Var
I looked online and it said to escape $ you have to use the backtick. Doesn't seem to work for variables though?

Maybe use the following syntax:
$Var = 'one'
$string = #"
This is a `$Var I want to escape and {0} I do not want to
"# -f $Var
$string
Generates the following output:
This is a $Var I want to escape and one I do not want to
Another option is embedding the variable:
#"
This is a `${Var} I want to escape and $Var I do not want to
"#
Some remarks:
A here string is always between double quotes #""#
To escape a character use the backtick `

I figured it out. You must put double brackets.
Example:
$string = #'
This is a ${{string}} I want to escape and {0} one I do not want to
'# -f $Var

Related

bash echo environment variable containing escaped characters

I have an script that echo the input given, into a file as follows:
echo $# > file.txt
When I pass a sting like "\"" I want it to exactly print "\"" to the file however it prints ".
My question is how can I print all characters of a variable containing a string without considering escapes?
When I use echo in bash like echo "\"" it only prints " while when I use echo '"\""' it prints it correctly. I thought maybe that would be the solution to use single quotes around the variable, however I cannot get the value of a variable inside single quotes.
First, note that
echo $# > file.txt
can fail in several ways. Shellcheck identifies one problem (missing quotes on $#). See the accepted, and excellent, answer to Why is printf better than echo? for others.
Second, as others have pointed out, there is no practical way for a Bash program to know exactly how parameters were specified on the command line. For instance, for all of these invocations
prog \"
prog "\""
prog '"'
the code in prog will see a $1 value that consists of one double-quote character. Any quoting characters that are used in the invocation of prog are removed by the quote removal part of the shell expansions done by the parent shell process.
Normally that doesn't matter. If variables or parameters contain values that would need to be quoted when entered as literals (e.g. "\"") they can be used safely, including passing them as parameters to other programs, by quoting uses of the variable or parameter (e.g. "$1", "$#", "$x").
There is a problem with variables or parameters that require quoting when entered literally if you need to write them in a way that they can be reused as shell input (e.g. by using eval or source/.). Bash supports the %q format specification to the printf builtin to handle this situation. It's not clear what the OP is trying to do, but one possible solution to the question is:
if (( $# > 0 )) ; then
printf -v quoted_params '%q ' "$#" # Add all parameters to 'quoted_params'
printf '%s\n' "${quoted_params% }" # Remove trailing space when printing
fi >file.txt
That creates an empty 'file.txt' when no positional parameters are provided. The code would need to be changed if that is not what is required.
If you run echo \", the function of the backslash in bash is to escape the character after it. This actually enables you to use the double quotes as an argument. You cannot use a backslash by itself; if you want to have a backslash as an argument you need to use another slash to escape that: echo \\
Now if you want to create a string where these things are not escaped, use single quotes: echo '\'
See for a better explanation this post: Difference between single and double quotes in Bash

Escape braces in ksh

I am trying to prepare JSON in ksh file. I am facing this problem - I think it's because I can't properly use braces. Example:
RESULT="[";
COUNTRY=mCountry
LANGUAGE=mLang
AppendParams()
{
RESULT=$RESULT"{\"site:\"$COUNTRY\",\"lang\":\"$LANGUAGE\"}";
}
AppendParams
RESULT=$RESULT"]";
echo $RESULT;
Output is:
sh-4.3$ ksh main.ksh
["site:"mCountry"] ["lang":"mLang"]
Instead of
[{"site:"mCountry","lang":"mLang"}]
Is there a way to disable braces or escape them? Please help.
When you echo or print a variable whose value might contain a brace, double-quote the variable name like "${VARIABLE}" to avoid brace expansion. Also you might use single quotes to avoid having to escape every double-quote. Try:
AppendParams()
{
RESULT=${RESULT}'{"site:"'${COUNTRY}'","lang":'${LANGUAGE}'"}'
}
AppendParams
RESULT=$RESULT"]"
echo "$RESULT"

why sed not working properly in script

Hi I have following line in shellscript
sed 's_$org_$repl_g' $i > $temp_file
In this $org denotes the name to be change and $repl denotes replacement. I have done echo for both and both are write. $i represent the file name. when I echo below
echo $(sed "s/$org/$repl_g" $i)
Then also it does not replace the word . while when I try this with terminal directly as below
sed 's_Dilip_Agarwal_g' test.txt
then it give correct output by replacing the original one.
Can any body help me where I am wrong in this.
Thanks
Do not use command substitution on it. And use double quotes instead of single quotes. Single quotes do not expand parameters. You also have to fix your parameter expansion. _ is also a valid parameter character so you need to use braces to isolate the only characters that would identify the parameters.
sed "s_${org}_${repl}_g" "$i" > "$temp_file"
You can also just use another delimeter that's not a parameter character:
sed "s|$org|$repl|g" "$i" > "$temp_file"

BASH: A variable inside a defined variable?

i have the following function in a bash script which does not work?
do_get() {
cmd='<command version="33" cmd="GETINFO" $3</command>'
echo $cmd
}
Now, if i echo $3 right before the cmd variable it echos out 1234 which i am passing as a 3 argument when executing this. BUT it shows just $3 when i do an echo $cmd.
i tried a couple of things like such below thinking its getting striped out
'$3' but it then shows blank
'"$3"' same as above
The variable doesn't expand when inside single quotes. You need to use double quotes instead, but since you have double quotes on the inside, you need to make sure you remember to escape those as well.
do_get() {
cmd="<command version=\"33\" cmd=\"GETINFO\" $3</command>"
echo $cmd
}
Newer versions of bash add a -v flag to the printf command that makes assignments like this a little easier on the eye, in that quoting is reduced.
printf -v cmd '<command version="33" cmd="GETINFO" %d </command' "$3"
The single quote in Bash prevents variable substitution. In order for the third parameter to be substituted, you should enclose your string in double quotes. of course, you have the problem of the double quotes that are part of your string, so they need to be escaped with a backslash:
cmd="<command version=\"33\" cmd=\"GETINFO\" $3 </command>"

Adding newline characters to unix shell variables

I have a variable in a shell script in which I'd like to format the data. The variable stores new data during every iteration of a loop. Each time the new data is stored, I'd like to insert a new line character. Here is how I'm trying to store the data into the variable.
VARIABLE="$VARIABLE '\n' SomeData"
Unfortunately, the output includes the literal '\n' Any help would be appreciative.
Try $'\n':
VAR=a
VAR="$VAR"$'\n'b
echo "$VAR"
gives me
a
b
A common technique is:
nl='
'
VARIABLE="PreviousData"
VARIABLE="$VARIABLE${nl}SomeData"
echo "$VARIABLE"
PreviousData
SomeData
Also common, to prevent inadvertently having your string start with a newline:
VARIABLE="$VARIABLE${VARIABLE:+$nl}SomeData"
(The expression ${VARIABLE:+$nl} will expand to a newline if and only if VARIABLE is set and non-empty.)
VAR="one"
VAR="$VAR.\n.two"
echo -e $VAR
Output:
one.
.two
Other than $'\n' you can use printf also like this:
VARIABLE="Foo Bar"
VARIABLE=$(printf "${VARIABLE}\nSomeData")
echo "$VARIABLE"
OUTPUT:
Foo Bar
SomeData
I had a problem with all the other solutions: when using a # followed by SPACE (quite common when writing in Markdown) both would get split onto a new line.
So, another way of doing it would involve using single quotes so that the "\n" get rendered.
FOO=$'# Markdown Title #\n'
BAR=$'Be *brave* and **bold**.'
FOOBAR="$FOO$BAR"
echo "$FOOBAR"
Output:
# Markdown Title #
Be *brave* and **bold**.
Single quote All special characters between these quotes lose their
special meaning.https://www.tutorialspoint.com/unix/unix-quoting-mechanisms.htm
So the syntax you use does something different that you want to achieve.
This is what you need:
The $'\X' construct makes the -e option in echo unnecessary.
https://linux.die.net/abs-guide/escapingsection.html
echo -e "something\nsomething"
or
echo "something"$'\n'"something"
It's a lot simpler than you think:
VARIABLE="$VARIABLE
SomeData"
Building upon the first two solutions, I'd do like shown below. Concatenating strings with the '+=' operator, somehow looks clearer to me.
Also rememeber to use printf as opposed to echo, you will save yourself so much trouble
sometext="This is the first line"
sometext+=$'\n\n'
sometext+="This is the second line AFTER the inserted new lines"
printf '%s' "${sometext}"
Outputs:
This is the first line
This is the third line AFTER the inserted new line
Your problem is in the echo command, in ash you have to use the option -e to expand special characters. This should work for you:
VAR="First line"
VAR="$VAR\nSecond line"
echo -e $VAR
This outputs
First line
Second line

Resources