Preparing output for further processing with Xargs
|
Do Nothing
Sometimes doing nothing is required. Many programs don't appreciate calls without parameters and will report an error. You can make GNU Xargs avoid calling the program if there are parameters (Listing 12). The BSD implementation already does this by default.
Listing 12
Skipping Calls with No Parameters
01 $ find . -name '*.bla' 02 $ find . -name '*.bla' | xargs file 03 Usage: file [-bchikLlNnprsvz0] [--apple] [--mime-encoding] [--mime-type] 04 [-e testname] [-F separator] [-f namefile] [-m magicfiles] file ... 05 file -C [-m magicfiles] 06 file [--help] 07 $ find . -name '*.bla' | xargs -r file
Teamwork
Find is not the only command that works well with Xargs. Xargs is also very useful when combined with grep . With the -l option, the program displays only the filenames that include a match. In Listing 13, for example, the software first searches in the current directory's files scanning for the < symbol. If finds it, it passes the name of the file on to Xargs. Xargs then passes this to file which determines the file type.
Listing 13
Xargs and Grep
01 $ grep -l '<' * | xargs file 02 bar.html: HTML document, ASCII text 03 foo.xml: XML document text
GNU grep from version 2.4 even recognizes the -Z option (for zero) that ends a filename with a null character instead of a line break, with the advantages mentioned above (Listing 14).
Listing 14
Grep with the -Z Option
01 $ grep -l foo * | xargs file 02 File: ERROR: cannot open `File' (No such file or directory) 03 with: ERROR: cannot open `with' (No such file or directory) 04 linebreaks.txt: ERROR: cannot open `linebreaks.txt' (No such file or directory) 05 bar.html: HTML document, ASCII text 06 foo.xml: XML document text 07 $ grep -lZ foo * | xargs -0 file 08 File 09 with 10 linebreaks.txt: ASCII text 11 bar.html: HTML document, ASCII text 12 foo.xml: XML document text
The Prips [7] program also works wonders together with Xargs. The name stands for "Print IPs" and the tool prints all the IP addresses for a given range of addresses.
Listing 15 shows an example in which I used the -n 1 option one more time. Here, the host command also processes only one IP address per call.
Listing 15
Prips Processed Output
01 $ prips 192.33.96.0/30 02 192.33.96.0 03 192.33.96.1 04 192.33.96.2 05 192.33.96.3 06 $ prips 192.33.96.0/30 | xargs -n 1 host 07 0.96.33.192.in-addr.arpa domain name pointer phys-hpx-dock-1.ethz.ch. 08 1.96.33.192.in-addr.arpa domain name pointer rou-hpx-1-phys-hpx-dock-1.ethz.ch. 09 2.96.33.192.in-addr.arpa domain name pointer floo.ethz.ch. 10 3.96.33.192.in-addr.arpa domain name pointer aragog.ethz.ch.
« Previous 1 2 3 4 Next »
Buy this article as PDF
Pages: 4
(incl. VAT)