Add Move A List Of Files To Another Directory as a Unix TIL

This commit is contained in:
jbranchaud
2026-07-15 09:02:08 -05:00
parent 096e5622d3
commit 5bc87154d3
2 changed files with 42 additions and 1 deletions
+2 -1
View File
@@ -10,7 +10,7 @@ working across different projects via [VisualMode](https://www.visualmode.dev/).
For a steady stream of TILs, [sign up for my newsletter](https://visualmode.kit.com/newsletter).
_1821 TILs and counting..._
_1822 TILs and counting..._
See some of the other learning resources I work on:
@@ -1817,6 +1817,7 @@ If you've learned something here, support my efforts writing daily TILs by
- [Make Neovim The Default Way To View Man Pages](unix/make-neovim-the-default-way-to-view-man-pages.md)
- [Manually Pass Two Git Files To Delta](unix/manually-pass-two-git-files-to-delta.md)
- [Map A Domain To localhost](unix/map-a-domain-to-localhost.md)
- [Move A List Of Files To Another Directory](unix/move-a-list-of-files-to-another-directory.md)
- [Negative Look-Ahead Search With ripgrep](unix/negative-look-ahead-search-with-ripgrep.md)
- [Occupy A Local Port With Netcat](unix/occupy-a-local-port-with-netcat.md)
- [Only Show The Matches](unix/only-show-the-matches.md)
@@ -0,0 +1,40 @@
# Move A List Of Files To Another Directory
Let's say I have some command I run (it doesn't matter what it is) that produces
a list of files I want to deal with. For instance, how about all the markdown
files in some directory -- `fd -e md . docs`.
Whatever that list of files is, I want to move them to another directory. To do
that I can pipe the list to `mv` via `xargs`. The built-in `mv` command on MacOS
can take a list of one or more source files followed by a single target
directory. So I need `xargs` to inject the filename for the current line being
processed into the middle of each `mv` that gets executed.
```bash
fd -e md . docs | xargs -IFILE mv FILE ../target/dir
# essentially:
# mv docs/file1.md ../target/dir
# mv docs/file2.md ../target/dir
# mv docs/file3.md ../target/dir
```
The `-I` flag lets me define a token (e.g. `FILE`) that represents a line from
the source input. I can then inject that token anywhere in the command that
`xargs` is evaluating. This `mv` command gets run once for each line (that is,
each file name) from the source input.
A slightly easier way to approach this if I have [GNU
CoreUtils](https://formulae.brew.sh/formula/coreutils) installed is to use their
version of `mv` ([which will be `gmv` for
me](/mac/access-coreutils-that-conflict-with-unix-utilities.md)) which has the
`-t` flag. With that form, I can specify the target directory first with `-t`
and then `xargs` can naturally inject all the file names from the source input
at the end of the line.
```bash
fd -e md . docs | xargs gmv -t ../target/dir
# essentially:
# gmv -t ../target/dir docs/file1.md docs/file2.md docs/file3.md
```
See `man xargs` as well as `man mv` and `man gmv` for more details.