Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

xargs - how to run only when something is found? 1

Status
Not open for further replies.

stfaprc

Programmer
Feb 10, 2005
216
US
the following line works fine:
ls -l | grep " 7" | cut -c 57-70 | xargs rm

except, I don't want the 'rm' to run if the grep come up empty. How do I write this so it only runs if the grep finds?
 
you may try this:
Code:
ls -l | awk '{/       7/{system("rm "substr($0,57,14))}'

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Where is the first closing curly bracket supposed to be?
I put it after the 7/ , and the line operated on every file and not just those 7 bytes large.
 
If you don't want to run rm just because of the Usage: rm [-Rfir] file ... message you get when it has no arguments, try using rm -f instead, because that never complain.

The other option is xargs -L n rm, which will only run the command if there is at least one argument being supplied. You will need to take a guess at a suitable value of n though, say 100?

Annihilannic.
 
OOps, sorry for the typo:
ls -l | awk '/ 7/{system("rm "substr($0,57,14))}'

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
The other option is xargs -L n rm, which will only run the command if there is at least one argument being supplied. You will need to take a guess at a suitable value of n though, say 100?

Annihilannic.
the man page does not mention that feature of -l .
Does this mean that 'xargs' actually causes one run of command, as opposed to the "awk" method which would run an individual instance of the command on each hit?

 
Unfortunately the xargs options seem to vary quite a lot on different operating systems; what OS are you using?

-L will do the trick on HP-UX or AIX. -r is the one you want on GNU/Linux systems.

Annihilannic.
 
sorry, mislead you.
running RH9 and it does list -l along with --max-lines.
What it does not say is that if there are NO lines then the xargs will not run at all.
 

Annihilannic said -r on Linux. Your RH is a Linux, so...

Code:
--no-run-if-empty, -r
              If the standard input does not contain any nonblanks, do not run the command.
              Normally, the command is run once even if there is no input.  This option is a GNU extension.

This is from a Debian box, should look similar in your man page.

laters
zaxxon
 
ohh, the -r is what is preventing the running. thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top