juechafun/05-原子化笔记本/Linux-xargs-标准输入转命令参数.md

64 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
#领域/Linux
#复盘/4
## 一句话描述
[__xargs 使用说明______]
---
## 核心示例
xargs 接收管道 / 标准输入的文本内容,把它转换成后续命令的「参数列表」,然后执行这个命令
### ✅ 基本用法
```bash
find . -name "*.log" | xargs rm -rf
```
### ✅ 生产环境用法
```bash
find [路径] [条件] -print0 | xargs -0 -I {} 目标命令 {} 固定参数
```
### ✅ 默认无占位符 vs. 自定义占位符
```bash
# 默认无占位符
ls *.txt | xargs rm -rf
# ls 输出a.txt b.txt
# xargs 拼接后执行rm -rf a.txt b.txt
# -I {} 指定占位符
find . -name "*.txt" | xargs -I {} mv {} /tmp/bak/{}.bak
# 命令A | xargs -I {} 目标命令 {} 固定参数
```
### ✅ 生产环境:兼容带空格/特殊字符的文件名
```bash
# user info.log 或 data|test.csv
# 默认空格会被当成参数分隔符
find [路径] [条件] -print0 | xargs -0 目标命令
# find -print0输出时使用空字符\0作为文件名的分隔符
# xargs -0接收时使用空字符\0作为分隔符
```
## 参数说明
- 默认无占位符,自动拼接参数列表->追加至末尾->执行命令,(默认将空格、制表符、换行符作为参数分隔符)
- -I {},指定占位符
- -print0 | xargs -0指定\0为文件名分隔符
| 选项 | 说明 |
| ---- | --------------- |
| -p | 执行前交互式确认 |
| -t | 执行前打印要执行的命令 |
| -n N | 每次只传递 N 个参数执行命令 |