Skip to content

Commit

Permalink
xargs -I {} 命令
Browse files Browse the repository at this point in the history
  • Loading branch information
magicianlib committed Nov 14, 2024
1 parent e75368e commit e89f113
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions 命令与最佳实战/xargs 实战技巧.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# 传递文件名

比如当前目录下有两个 7z 文件:

```bash
$ ls | grep 7z
TreeSizeFree-Portable.zip.7z
TreeSizeFreeSetup.exe.7z
```

我想实现的效果是直接使用管道命令进行解压,如下:

```bash
$ ls | grep 7z | 7z x -
```

显而易见,执行失败。原因是因为 7z 命令需要的是一个文件名,但是 `-` 是一个标准输入流(会将上一个管道的输出作为该管道的输入)。

解决方法就是可以考虑使用 xargs 命令的 `-I` 参数了:

```bash
$ ls | grep 7z | xargs -I {} 7z x {}
```

`xargs -I {}` 将每个匹配的文件名替换到 `{}` 中,并执行 `7z x {}` 进行解压。

`{}``xargs` 中的一个占位符,表示将匹配到的内容替换到它所在的位置。不过,它不是固定的符号,你可以使用其他字符来代替 `{}`。只要确

只要确保替换符号(`-I <替换符号>`)在命令中没有引起歧义,就可以使用任意字符代替。 比如使用 `@`

```bash
$ ls | grep 7z | xargs -I @ 7z x @
```

0 comments on commit e89f113

Please sign in to comment.