Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xargs - place the argument in a different location in the command

Tags:

xargs

Let's say I want to write a script that does ls with a prefix for each filename. I tried this

ls | xargs -n 1 echo prefix_ 

But the result was

prefix_ first_file prefix_ second_file ... 

How can I remove the space between the prefix and the filename? I.e. how to I make xargs put the variable after the command, without space? (Or in any other place for that matter)

like image 851
Dotan Avatar asked Oct 18 '17 11:10

Dotan


People also ask

How do you pass arguments to xargs?

The -c flag to sh only accepts one argument while xargs is splitting the arguments on whitespace - that's why the double quoting works (one level to make it a single word for the shell, one for xargs).

What does the xargs command do?

The xargs command builds and executes commands provided through the standard input. It takes the input and converts it into a command argument for another command. This feature is particularly useful in file management, where xargs is used in combination with rm , cp , mkdir , and other similar commands.

How do you use xargs with multiple arguments?

Two Types of Commands Using Multiple Arguments Commands can have multiple arguments in two scenarios: All command arguments – COMMAND ARG1 ARG2 ARG3. Option arguments – for example, COMMAND -a ARG1 -b ARG2 -c ARG3.

What is xargs option?

xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input.


1 Answers

The solution: -I

-I lets you name your argument and put it anywhere you like. E.g.

ls | xargs -n 1 -I {} echo prefix_{} 

(replace {} with any string)

like image 176
Dotan Avatar answered Oct 02 '22 15:10

Dotan