jpskill.com
💼 ビジネス コミュニティ

xargs-parallel

Parallel execution with xargs, GNU parallel, and batch processing patterns. Use when user mentions "xargs", "parallel", "batch processing", "run in parallel", "parallel execution", "process list of files", "bulk operations", "concurrent commands", "map over files", or running commands on multiple inputs.

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-17
取得日時
2026-05-17
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

[Skill 名] xargs-parallel

xargsと並列実行

xargsの基本

標準入力から読み込み、コマンドへの引数として渡します。

# 基本的な使い方: 標準入力の行を引数として渡す
echo "file1.txt file2.txt" | xargs rm

# -I {} は各入力行のプレースホルダーを設定します
cat urls.txt | xargs -I {} curl -O {}

# -n はコマンド呼び出しごとの引数の数を制御します
echo "a b c d e f" | xargs -n 2 echo
# 出力:
# a b
# c d
# e f

# -t は実行前に各コマンドを表示します (トレースモード)
ls *.log | xargs -t rm

# ファイルから引数を読み込む
xargs -a filelist.txt rm

findとxargs

スペースや特殊文字を含むファイル名を処理するために、常に-print0 / -0を使用してください。

# パターンに一致するファイルを安全に削除する
find . -name "*.tmp" -print0 | xargs -0 rm -f

# すべてのPythonファイルの行数を数える
find . -name "*.py" -print0 | xargs -0 wc -l

# 特定のファイルのパーミッションを変更する
find /var/log -name "*.log" -print0 | xargs -0 chmod 644

# findで見つかったファイル全体をgrepする
find src/ -name "*.js" -print0 | xargs -0 grep -l "TODO"

xargs -Pによる並列実行

-P Nは最大N個のプロセスを並列で実行します。

# 4つの並列ジョブを使用してファイルを圧縮する
find . -name "*.log" -print0 | xargs -0 -P 4 -I {} gzip {}

# URLを並列でダウンロードする (一度に8つ)
cat urls.txt | xargs -P 8 -I {} curl -sO {}

# 画像を並列で変換する
find . -name "*.png" -print0 | xargs -0 -P 4 -I {} convert {} -resize 50% resized_{}

# 利用可能なすべてのコアを使用する
find . -name "*.gz" -print0 | xargs -0 -P "$(nproc)" gunzip

GNU parallelの基本

GNU parallelは、インストールされている場合により多くの機能を提供します(brew install parallel / apt install parallel)。

# 基本的な使い方 (xargs -Pに似ています)
cat urls.txt | parallel curl -sO {}

# ジョブ数を制御する
find . -name "*.csv" | parallel -j 8 gzip {}

# プログレスバー
find . -name "*.mp4" | parallel --bar ffmpeg -i {} -vf scale=640:-1 small_{}

# 失敗したジョブを再試行する
cat urls.txt | parallel --retries 3 curl -sO {}

# 複数のマシン (SSH) にジョブを分散する
parallel -S server1,server2 --transferfile {} gzip ::: *.log

# 出力順序を入力順序と一致させる
seq 10 | parallel -k 'sleep $((RANDOM % 3)); echo {}'

一般的なパターン

ファイルの一括リネーム

# プレフィックスを追加する
ls *.jpg | xargs -I {} mv {} archive_{}

# 拡張子を変更する (サブシェルでパラメータ展開を使用)
find . -name "*.txt" -print0 | xargs -0 -I {} bash -c 'mv "$1" "${1%.txt}.md"' _ {}

# 現在のディレクトリ内のすべてのファイル名を小文字にする
ls | xargs -I {} bash -c 'mv "$1" "$(echo "$1" | tr "A-Z" "a-z")"' _ {}

パターンに一致するすべてのファイルを処理する

# すべてのGoファイルをフォーマットする
find . -name "*.go" -print0 | xargs -0 gofmt -w

# すべてのJSファイルをLintする
find src/ -name "*.js" -print0 | xargs -0 eslint --fix

# 各設定ファイルに対してスクリプトを実行する
find /etc -name "*.conf" -print0 | xargs -0 -I {} ./validate-config.sh {}

URLリストのダウンロード

# ファイルからすべてのURLをダウンロードする (10個並列)
cat urls.txt | xargs -P 10 -I {} curl -sfLO {}

# wgetでダウンロードし、失敗を再試行する
cat urls.txt | xargs -P 5 -I {} wget -q --retry-connrefused --tries=3 {}

# GNU parallelとプログレスバーを使用する
parallel --bar -j 10 curl -sfLO {} < urls.txt

テストの並列実行

# テストファイルを並列で実行する
find tests/ -name "test_*.py" | xargs -P 4 -I {} python -m pytest {} -v

# 複数のテストスイートを同時に実行する
echo "unit integration e2e" | xargs -n 1 -P 3 -I {} make test-{}

バッチAPI呼び出し

# 各JSONファイルをAPIエンドポイントにPOSTする
find data/ -name "*.json" -print0 | xargs -0 -P 5 -I {} \
  curl -s -X POST -H "Content-Type: application/json" -d @{} https://api.example.com/ingest

# ファイルからユーザーIDを処理する
cat user_ids.txt | xargs -P 10 -I {} \
  curl -s "https://api.example.com/users/{}" -o "responses/{}.json"

並列画像圧縮

# pngquantでPNGを並列で圧縮する
find . -name "*.png" -print0 | xargs -0 -P "$(nproc)" -I {} pngquant --force --quality=65-80 {} --output {}

# ImageMagickでJPEGのサイズを変更する
find photos/ -name "*.jpg" -print0 | xargs -0 -P 4 -I {} \
  convert {} -resize 1920x1080\> -quality 85 optimized/{}

リポジトリ全体での一括Git操作

# ディレクトリ下のすべてのリポジトリで最新をプルする
find ~/projects -maxdepth 2 -name ".git" -type d -print0 | \
  xargs -0 -P 8 -I {} git -C "{}/.." pull --ff-only

# すべてのリポジトリのステータスを確認する
find ~/projects -maxdepth 2 -name ".git" -type d | \
  xargs -I {} bash -c 'echo "=== $(dirname {}) ===" && git -C "{}/.." status -s'

# すべてのリポジトリを並列でガベージコレクションする
find ~/projects -maxdepth 2 -name ".git" -type d -print0 | \
  xargs -0 -P 4 -I {} git -C "{}/.." gc --quiet

スペースを含むファイル名の処理

# -0 はヌル区切りの入力を期待します (find -print0と組み合わせて使用)
find . -name "*.txt" -print0 | xargs -0 wc -l

# -d '\n' は改行を区切り文字として扱います (スペースではない)
ls | xargs -d '\n' -I {} echo "File: {}"

# macOS (BSD xargsには-dがない) では、trと-0を使用します
ls | tr '\n' '\0' | xargs -0 -I {} echo "File: {}"

実行前のドライラン

# 削除されるものをプレビューする
find . -name "*.bak" -print0 | xargs -0 echo rm

# 各実行前にプロンプトを表示するために-pを使用する
find . -name "*.tmp" -print0 | xargs -0 -p rm

# 実行中のコマンドをトレースするために-tを使用する
find . -name "*.log" -print0 | xargs -0 -t gzip

エラー処理

# いずれかのコマンドが失敗した場合、xargsは123で終了します
find . -name "*.sh" -print0 | xargs -0 -P 4 bash  # $? を確認

# GNU parallel: 最初の失敗で停止する
cat jobs.txt | parallel --halt now,fail=1 process_job {}

# GNU parallel: ジョブの20%が失敗した場合に停止する
cat jobs.txt | parallel --halt soon,fail=20% process_job {}

# GNU parallelでジョブごとの終了コードをキャプチャする
cat jobs.txt | parallel --joblog joblog.txt process_job {}
# joblog.txtにはすべてのジョブの終了ステータスが含まれます

xargs vs forループ vs while read

xargsを使用する場合:

  • findまたは別のコマンドからの出力を処理する場合
  • 組み込みの並列処理 (-P) を利用したい場合
  • 呼び出しごとに複数の引数をバッチ処理する場合 (-n)

whileを使用する場合:

(原文がここで切り詰められています)

📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

xargs and Parallel Execution

xargs Basics

Read from stdin and pass as arguments to a command:

# Basic usage: pass stdin lines as arguments
echo "file1.txt file2.txt" | xargs rm

# -I {} sets a placeholder for each input line
cat urls.txt | xargs -I {} curl -O {}

# -n controls how many arguments per command invocation
echo "a b c d e f" | xargs -n 2 echo
# Output:
# a b
# c d
# e f

# -t prints each command before executing (trace mode)
ls *.log | xargs -t rm

# Read arguments from a file
xargs -a filelist.txt rm

xargs with find

Always use -print0 / -0 to handle filenames with spaces and special characters:

# Safe deletion of files matching a pattern
find . -name "*.tmp" -print0 | xargs -0 rm -f

# Count lines in all Python files
find . -name "*.py" -print0 | xargs -0 wc -l

# Change permissions on specific files
find /var/log -name "*.log" -print0 | xargs -0 chmod 644

# Grep across files found by find
find src/ -name "*.js" -print0 | xargs -0 grep -l "TODO"

Parallel Execution with xargs -P

-P N runs up to N processes in parallel:

# Compress files using 4 parallel jobs
find . -name "*.log" -print0 | xargs -0 -P 4 -I {} gzip {}

# Download URLs in parallel (8 at a time)
cat urls.txt | xargs -P 8 -I {} curl -sO {}

# Convert images in parallel
find . -name "*.png" -print0 | xargs -0 -P 4 -I {} convert {} -resize 50% resized_{}

# Use all available cores
find . -name "*.gz" -print0 | xargs -0 -P "$(nproc)" gunzip

GNU parallel Basics

GNU parallel offers more features if installed (brew install parallel / apt install parallel):

# Basic usage (similar to xargs -P)
cat urls.txt | parallel curl -sO {}

# Control job count
find . -name "*.csv" | parallel -j 8 gzip {}

# Progress bar
find . -name "*.mp4" | parallel --bar ffmpeg -i {} -vf scale=640:-1 small_{}

# Retry failed jobs
cat urls.txt | parallel --retries 3 curl -sO {}

# Distribute jobs across multiple machines (SSH)
parallel -S server1,server2 --transferfile {} gzip ::: *.log

# Keep output order matching input order
seq 10 | parallel -k 'sleep $((RANDOM % 3)); echo {}'

Common Patterns

Bulk Rename Files

# Add a prefix
ls *.jpg | xargs -I {} mv {} archive_{}

# Change extension (using parameter expansion in a subshell)
find . -name "*.txt" -print0 | xargs -0 -I {} bash -c 'mv "$1" "${1%.txt}.md"' _ {}

# Lowercase all filenames in current directory
ls | xargs -I {} bash -c 'mv "$1" "$(echo "$1" | tr "A-Z" "a-z")"' _ {}

Process All Files Matching a Pattern

# Format all Go files
find . -name "*.go" -print0 | xargs -0 gofmt -w

# Lint all JS files
find src/ -name "*.js" -print0 | xargs -0 eslint --fix

# Run a script against each config file
find /etc -name "*.conf" -print0 | xargs -0 -I {} ./validate-config.sh {}

Download a List of URLs

# Download all URLs from a file, 10 in parallel
cat urls.txt | xargs -P 10 -I {} curl -sfLO {}

# Download with wget, retrying failures
cat urls.txt | xargs -P 5 -I {} wget -q --retry-connrefused --tries=3 {}

# With GNU parallel and a progress bar
parallel --bar -j 10 curl -sfLO {} < urls.txt

Run Tests in Parallel

# Run test files in parallel
find tests/ -name "test_*.py" | xargs -P 4 -I {} python -m pytest {} -v

# Run multiple test suites concurrently
echo "unit integration e2e" | xargs -n 1 -P 3 -I {} make test-{}

Batch API Calls

# POST each JSON file to an API endpoint
find data/ -name "*.json" -print0 | xargs -0 -P 5 -I {} \
  curl -s -X POST -H "Content-Type: application/json" -d @{} https://api.example.com/ingest

# Process user IDs from a file
cat user_ids.txt | xargs -P 10 -I {} \
  curl -s "https://api.example.com/users/{}" -o "responses/{}.json"

Parallel Image Compression

# Compress PNGs in parallel with pngquant
find . -name "*.png" -print0 | xargs -0 -P "$(nproc)" -I {} pngquant --force --quality=65-80 {} --output {}

# Resize JPEGs with ImageMagick
find photos/ -name "*.jpg" -print0 | xargs -0 -P 4 -I {} \
  convert {} -resize 1920x1080\> -quality 85 optimized/{}

Bulk Git Operations Across Repos

# Pull latest in all repos under a directory
find ~/projects -maxdepth 2 -name ".git" -type d -print0 | \
  xargs -0 -P 8 -I {} git -C "{}/.." pull --ff-only

# Check status of all repos
find ~/projects -maxdepth 2 -name ".git" -type d | \
  xargs -I {} bash -c 'echo "=== $(dirname {}) ===" && git -C "{}/.." status -s'

# Garbage collect all repos in parallel
find ~/projects -maxdepth 2 -name ".git" -type d -print0 | \
  xargs -0 -P 4 -I {} git -C "{}/.." gc --quiet

Handling Filenames with Spaces

# -0 expects null-delimited input (pair with find -print0)
find . -name "*.txt" -print0 | xargs -0 wc -l

# -d '\n' treats newlines as delimiters (not spaces)
ls | xargs -d '\n' -I {} echo "File: {}"

# On macOS (BSD xargs lacks -d), use -0 with tr
ls | tr '\n' '\0' | xargs -0 -I {} echo "File: {}"

Dry Run Before Executing

# Preview what would be deleted
find . -name "*.bak" -print0 | xargs -0 echo rm

# Use -p to prompt before each execution
find . -name "*.tmp" -print0 | xargs -0 -p rm

# With -t to trace commands as they run
find . -name "*.log" -print0 | xargs -0 -t gzip

Error Handling

# xargs exits with 123 if any command fails
find . -name "*.sh" -print0 | xargs -0 -P 4 bash  # check $?

# GNU parallel: halt on first failure
cat jobs.txt | parallel --halt now,fail=1 process_job {}

# GNU parallel: halt when 20% of jobs fail
cat jobs.txt | parallel --halt soon,fail=20% process_job {}

# Capture per-job exit codes with GNU parallel
cat jobs.txt | parallel --joblog joblog.txt process_job {}
# joblog.txt contains exit status for every job

xargs vs for Loops vs while read

Use xargs when:

  • Processing output from find or another command
  • You want built-in parallelism (-P)
  • Batching multiple arguments per invocation (-n)

Use while read when:

  • You need complex logic per iteration (if/else, multiple commands)
  • The loop body uses shell variables that must persist across iterations

Use for loops when:

  • Iterating over a known, small list of items
  • Glob expansion is sufficient (for f in *.txt)
  • Readability matters more than performance
# for loop -- simple, readable, no parallelism
for f in *.txt; do wc -l "$f"; done

# while read -- complex logic per item
find . -name "*.csv" | while read -r f; do
  count=$(wc -l < "$f")
  [ "$count" -gt 1000 ] && echo "Large: $f ($count lines)"
done

# xargs -- fast, parallel, concise
find . -name "*.csv" -print0 | xargs -0 -P 4 wc -l

Resource-Aware Parallelism

# Use nproc to match available CPU cores
find . -name "*.gz" -print0 | xargs -0 -P "$(nproc)" gunzip

# Use half the cores to leave room for other work
find . -name "*.log" -print0 | xargs -0 -P "$(( $(nproc) / 2 ))" gzip

# GNU parallel: percentage-based, relative, or load-based limits
parallel -j 50% gzip ::: *.log         # 50% of cores
parallel -j -2 gzip ::: *.log          # cores minus 2
parallel --load 80% process_job ::: *  # limit by load average

# Limit concurrency for I/O-bound tasks (network, disk)
cat urls.txt | xargs -P 5 -I {} curl -sO {}

# Monitor parallel job resource usage
parallel --joblog jobs.log -j 4 heavy_task ::: input_* && column -t jobs.log