Tuesday, 14 April 2015

xargs command: Tips and Tricks


Xargs is a powerful command. When we use "grep" or "find" commands, at times the output is a long listing of arguments. We often want to remove them or perform some kind of operation on that long listing. In Linux OS, such long listing of arguments is not accepted.

xargs helps us to overcome this hurdle by dividing such long listing of arguments into sub-list with acceptable length.

Some of its examples are:

Example 1: With and without xargs:

Imagine we need to use "find" command to get the list of files starting with name "file" inside the current working directory.

The following image depicts the difference in result, when using "xargs" and when we are not.

The first scenario is when we are not using "xargs". The output result is a list of files, in which each one is considered as a separate argument.

Whereas, the one which is highlighted gives the output as a single line.

Example 2: When used with grep.
It is a common scenario, when we use "find" to get the list of files and after that grep for a word.

An example:
find . -name "file*" | xargs grep -i "manoj"

In the above example, we used find to get the list of files starting with name "file"  and we used that result to grep for the word "manoj" in any of that file.

Example 3: To remove "tmp" files
Another common scenario is to remove "tmp" files from the current working directory.

An example:
find /tmp -name "*.tmp" | xargs rm

The above command will not work as expected, if any of the file contain a new line or space on it. To avoid this, we use the following command.
find /tmp -name "*.tmp" -print0 | xargs -0 rm

Example 4: Passing subset of arguments to xargs.
We can use "-n" flag to instruct the "xargs" on  how many arguments it should pass to a given command.

The following image will shows the usefulness of this option:

These are some of the common usage of xargs. Keep experimenting from your side to find more, according to the situations.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.