简体   繁体   中英

Finding multiple attributes present in an xml with certain conditions using shell scripting

grep -R --include="*.xml" "Frontal Face" /home/ashutosh/Desktop/imgdone | grep -v "Non Frontal Face"

This command gives me all xmls where "Frontal Face" is present. If I want to search more attributes through this shell script like "Happy", "Young" (occuring in the xml), what changes shall I do in this?

In summary, how to search for multiple attributes?

As already pointed out in the answers and comments to your previous question , there is nothing here which supports specifically searching for XML attributes. grep is not a good tool for searching structured formats, as already pointed out numerous times .

If your question is simply "how do I find X, Y, or Z anywhere in a file", that's trivial; grep -E 'X|Y|Z' files . But this does nothing to exclude matches which are not in XML attributes, or to find matches which are somehow obscured by the features of XML (such as X also being validly representable as X or a number of variants of this). Again, this was already pointed out to you previously.

While an XPath expression could be written to say "find any element in the parsed element tree with an attribute whose value is 'baz' or 'quux'", that's not really a sane requirement. Usually, you'd want something like "find any foo element in the tree whose bar attribute is 'baz' or 'quux', ie matches the regular expression ^(baz|quux)$ " which is

//foo/@bar[matches(.,'^(baz|quux)$')]

The matches() predicate is an XPath 2.0 feature.

You'd use it something like

find /home/ashutosh/Desktop/imgdone -type f -name '*.xml' -exec \
    xmllint --xpath '//foo/@bar[matches(., "^(baz|quux)$")]' {} \;

If your shell is new enough, you can drop the find command and just use a recursive wildcard like /home/ashutosh/Desktop/imgdone/**/*.xml as the file name argument to xmllint .

If you don't have xmllint , look for xmlstarlet or really any other XPath tool; there is no single ubiquitous standard utility for this (yet).

If you need to search specific elements like attributes or values within your xml structure, xsltproc or xmllint are the way to go, as tripleee has pointed out.

If you just need some "give lines with X or Y" in the same sentence, you can do something like this:

grep -E 'X|Y' file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM