Format all XML files in a directory and save them in a subdirectory
Asked Answered
J

1

5

I'm trying to write a script that will look through a directory, find all the XML files, run them through xmllint, and save the formatted results to a file of the same name in a subdirectory called formatted. Here's the script I have so far:

find . -maxdepth 1 -type f -iname "*.xml" | xargs -I '{}' xmllint --format '{}' > formatted/'{}'

This works, to an extent. The subdirectory ends up with one file, named "{}", which is just the results of the final file that was processed through xmllint. How can I get the files to write properly to the subdirectory?

Junkman answered 13/12, 2013 at 22:35 Comment(0)
F
13

The file named {} that you see should probably contain all of the formatted files together. The reason for this is that the redirection that you are using is not actually a part of the command that xargs sees. The redirection is interpreted by the shell, so what it does is run

find . -maxdepth 1 -type f -iname "*.xml" | xargs -I '{}' xmllint --format '{}'

and save the output to the file named formatted/{}.

Try using the --output option of xmllint instead of the redirection:

... | xargs -I '{}' xmllint --format '{}' --output formatted/'{}'

You can also avoid calling xargs by using the -exec option of find:

find . -maxdepth 1 -type f -iname "*.xml" -exec xmllint --format '{}' --output formatted/'{}' \;
Foolscap answered 13/12, 2013 at 22:47 Comment(2)
Thanks, didn't know about the --output option for xmllint. I tested both solutions (with xargs and with -exec) and they both work perfectly. Interestingly, the find man page mentions that "only one instance of '{}' is allowed within the command" when you use -exec, which is why I originally had opted for xargs, but it worked just fine.Junkman
@Junkman In my version of the man page, the phrase is there for the -exec command {} + syntax, but here the -exec command ; syntax is used, which is described several lines above in the man page.Foolscap

© 2022 - 2024 — McMap. All rights reserved.