Escaping the Exclamation Point in Grep

How do I escape an exclamation mark in bash?

Exclamation mark is preserved literally when you include it in a single-quoted string.

Example:

git commit -m 'Frustrating <insert object of frustration here>!'

Exclamation mark inside double quotes results in a strange parse error

You can wrap the string in single quotes instead of double quotes.

The exclamation point invokes the very useful history expansion function described in the bash manual.

History expansions are introduced by the appearance of the history expansion character, which is ! by default. Only \ and ' may be used to escape the history expansion character.

For instance, to execute the last command that started with the word mysql type this:

!mysql

or to execute the last command containing the word grep, type this:

!?grep

The bash manual also documents the syntax of the history expansion operators.

How to escape exclamation mark from 'command' using FOR /F?

From the syntax used (%L) you are running it in the command line, and from this context the command setlocal enabledelayedexpansion has no effect. If you read setlocal /? you will see this command is for batch files.

So, the real problem is that !FOO! is parsed as a literal as delayed expansion is not active (the default cmd configuration).

How to do it from command line? Enabling the delayed expansion for the cmd instance

set "FOO=bar"
cmd /v /c"for /F %L in ('echo !FOO!') do echo %L"

Note that the expansion of the !FOO! variable is done inside the cmd /v /c instance, not inside the cmd instance started to execute the echo command.

Bash:Single Quotes and Double Quotes and Exclamation Mark

$ cat t.sh
#! /bin/bash
echo -e $@

Or echo -e $1, or echo -e ${1} if you just want to process the first argument.

To get bash to stop trying to expand !, use set +H (see In bash, how do I escape an exclamation mark?)

$ set +H
$ ./t.sh "#1. You're smart!\n#2. It's a difficult question!"
#1. You're smart!
#2. It's a difficult question!

How to escape double quotes and exclamation mark in password?

Do not try to generate JSON manually; use a program like jq, which knows how to escape things properly, to generate it for you.

json=$(jq -n --arg u "$1" --arg p "$2" '{username: $u, password: $p}')
curl -s --insecure -H "Content-Type: application/json" -X POST -d "$json" http://apiurl

How to escape a question mark in R?

You have to escape \ as well:

vectorOfStrings <- c("Where is Waldo?", "I don't know", "This is ? random ?")
grep("\\?", vectorOfStrings)
#-----
[1] 1 3


Related Topics



Leave a reply



Submit