ogs
ogs

Reputation: 1239

Test if specific xml string exists in a file

I would like to test if the xml header exists in a specified file.

I am using something like :

FILE=${1}
PATTERN="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>"
if grep -Fxq ${PATTERN} ${FILE}
then
    echo "already exists"
else
    echo "not exists"
fi

But it returns :

grep: version="1.0": No such file or directory
grep: encoding="UTF-8": No such file or directory
grep: standalone="no"?>: No such file or directory
not exists

However, the PATTERN already exists in the file. Basically I just would like not create a new PATTERN line if it already exists in the specified file.

Upvotes: 1

Views: 2002

Answers (1)

dinox0r
dinox0r

Reputation: 16039

Enclose ${PATTERN} between double quotes: "${PATTERN}"

The following should work:

FILE=${1}
PATTERN="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>"
if grep -Fxq "${PATTERN}" ${FILE}
then
    echo "already exists"
else
    echo "not exists"
fi

What is happening without quote, is that the if command is expanded to grep -Fxq <?xml version.... and so version, and the other part are interpreted as argument, so grep will search for the corresponding file, which of course does not exist

Upvotes: 1

Related Questions