Friday, November 20, 2009

More Xargs

just learned the coolest xargs trick today. normally xargs can only represent one input symbol using the -I, but you can make it multiply by combining xargs with "sh -c". example:

ls --format=single-column | xargs -n1 sh -c 'g++ -g $1 -o ${1%.cpp}' -

takes all files from the current directory, each line contains 1 file name, pass it to xargs, which executes sh -c 'g++ -g $1 -o ${1%.cpp}' - where the file name will be used as the $1 variable for the shell, - is used as placeholder for $0, and ${1%.cpp} shrinks the file of .cpp string at the end if it contains it. sh is used to execute an command if -c is used

This way we can access multiple variables with xargs, each can be placed in different locations of the command we want to execute.

No comments: