Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass output as an argument for cp in bash [duplicate]

Tags:

linux

bash

unix

cp

ls

I'm taking a unix/linux class and we have yet to learn variables or functions. We just learned some basic utilities like the flag and pipeline, output and append to file. On the lab assignment he wants us to find the largest files and copy them to a directory.

I can get the 5 largest files but I don't know how to pass them into cp in one command

ls -SF | grep -v / | head -5 | cp ? Directory 
like image 345
Yamiko Avatar asked Jul 26 '11 16:07

Yamiko


People also ask

Does Bash cp overwrite?

By default, cp will overwrite files without asking. If the destination file name already exists, its data is destroyed. If you want to be prompted for confirmation before files are overwritten, use the -i (interactive) option.

How do you pass the output of one command as input to another in Linux?

You can make it do so by using the pipe character '|'. Pipe is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command's output may act as input to the next command and so on.

What is xargs command in Bash?

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 I duplicate a file in Bash?

Copy a File ( cp ) You can also copy a specific file to a new directory using the command cp followed by the name of the file you want to copy and the name of the directory to where you want to copy the file (e.g. cp filename directory-name ).


1 Answers

It would be:

cp `ls -SF | grep -v / | head -5` Directory 

assuming that the pipeline is correct. The backticks substitute in the line the output of the commands inside it.

You can also make your tests:

cp `echo a b c` Directory 

will copy all a, b, and c into Directory.

like image 186
Diego Sevilla Avatar answered Sep 17 '22 13:09

Diego Sevilla