Julian H. Lam
Julian H. Lam

Reputation: 26134

Way to change xargs arguments to include a flag per argument?

I have some passing experience with xargs, but I don't quite know how to do this:

I can use xargs to accomplish this:

tarsnap --list-archives | grep 2014-06-09 | xargs -n 1 tarsnap -df

However this runs tarsnap over and over again with one argument at a time (which is expected):

tarsnap -df 2014-06-09-00
tarsnap -df 2014-06-09-01
tarsnap -df 2014-06-09-02
... etc ...

The tarsnap documentation states that you can delete multiple archives by passing in multiple -f flags:

tarsnap -d -f 2014-06-09-00 -f 2014-06-09-01 -f 2014-06-09-02 # ... and so on

Is there a way to accomplish this with xargs?

(Aside: It might be pointless to even do this, since I have a feeling running tarsnap with multiple -f flags just causes tarsnap to run itself multiple times, one argument at a time... but I could be wrong)

Upvotes: 4

Views: 2155

Answers (4)

markhellewell
markhellewell

Reputation: 26090

You can actually do this with xargs

$ archivelist=$(tarsnap --list-a|xargs -I {} echo "-f {} ")
$ echo $archivelist
-f 2014-06-09-00 -f 2014-06-09-01 -f 2014-06-09-02 -f 2014-06-09-03 

Upvotes: 6

Ole Tange
Ole Tange

Reputation: 33725

If tarsnap accepts no space (i.e. -f2014-06-09) you can use GNU Parallel with context replace:

tarsnap --list-archives | parallel -Xj1 tarsnap -d -f{}

Upvotes: 0

Lev Levitsky
Lev Levitsky

Reputation: 65811

Using the idea quite similar to @choroba's, you can get rid of grep altogether and use sed instead:

tarsnap --list-archives | sed -n '/2014-06-09/s/^/-f /p' | xargs tarsnap -d

Upvotes: 2

choroba
choroba

Reputation: 241978

You can inject -f to the list before every item with sed:

tarsnap --list-archives | grep 2014-06-09 | sed 's/^/-f /' | xargs tarsnap -d

Upvotes: 2

Related Questions