Piping ls command output to cp or mv commands in Linux / Unix

Jay
1 min readSep 16, 2021

--

Recently I had a task move or copy few files from one directory to another directory. In Linux, we can do this in multiple ways like using ls command xargs, find command, or while loop with ls or find…..etc.

Piping ls command output to cp or mv

I have used the first option i.e., ls command with xargs.

$ ls /source/directory | xargs -i cp {} /destionation/copy/directory

Example :

Need to move all JSON files to the destination folder

Before moving:

$ tree
.
├── destination
└── source
├── file1.json
├── file1.txt
├── file2.json
├── file2.txt
├── file3.json
├── file3.txt
├── file4.json
└── file4.txt

After moving :

$ ls source/*.json | xargs -i mv {} destination/
$ tree
.
├── destination
│ ├── file1.json
│ ├── file2.json
│ ├── file3.json
│ └── file4.json
└── source
├── file1.txt
├── file2.txt
├── file3.txt
└── file4.txt

Thanks for reading this post, will continue to add my daily tasks and the solutions which I applied. Please follow me to get notifications for new posts.

--

--

No responses yet