xargs command in Linux

xargs command is designed to construct argument lists and invoke other utility. xargs reads items from the standard input or pipes, delimited by blanks or newlines, and executes the command one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored.

find . -type f | xargs grep "my_pattern"    # find a pattern in a file
find . -type f -print0 | xargs -0 sed -i 's/old_stuff/new_stuff/g'    # Find and replace a pattern in many files
find . -name "*.cpp" -print0 | xargs -0 grep -I "CreateStatement"    # Search within all .cpp files to find pattern CreateStatement, -I: ignore binary files.
find . -type d -print0 | xargs -0 chmod 775    # change all the directories' permission to 775
find . -type f -print0 | xargs -0 chmod 664    # change all the files' permission to 664

Note: -print0 option for find. Print full file name on standard output, followed by a null char (instead of newline -print uses). This option corresponds to the -0 option of xargs.

-0 option for xargs. Inputs are terminated by a null char. Quotes and backslash are not special (every char is taken literally). Useful when input might contain white space, quote marks, or backslashes. find -print0 option produces input suitable for this mode.

This entry was posted in Linux. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s