I'm a big fan of the xargs command. It's widely used in shell scripts but not so much on the command line. It's a really handy command when you want to take an incoming argument and apply a command to it. Here's an example that would kill every process matching a given pattern of "firefox" (similar to killall).
ps aux | grep firefox | awk '{print $2}' | xargs kill -9
remove files matching *lock*:
ls *lock* | xargs rm
for more complex commands, you can set the incoming data to be stored in a token:
ls *lock* | xargs -I $ ls -l $
or
ls *lock | xargs -I {} ls -l {}
Obviously the possibilities go far beyond what's shown here. Play around with it.
Thursday, March 13, 2008
Subscribe to:
Post Comments (Atom)
3 comments:
> ls *lock* | xargs rm
rm *lock*
That was easy ;-)
This is all wrong!!! NEVER, EVER parse the output of ls. ls' output is not meant to be parsed!!!
For example, try this:
# Create test files (with a space in the name)
touch hello\ {1..10}.lock
# try your stupid command: Surprise...
ls *lock* | xargs rm
Most of the time you'll be fine if you leave xargs alone (i.e., do not use xargs, there's always a better way to do it --- especially if your method involves parsing the output of some other program).
Dude, I like your vim tips better.
It is strange to know that output is not meant to be parsed for probably most often user _UNIX_ command.
ls -1 *lock* | sed -e "s/\(.\+\)/'\1'/" | xargs rm
or, if one decides to read man ls:
ls -1Q *lock* | xargs rm
Post a Comment