sed-awk
コマンドラインからテキストを効率的に処理し、ファイル内の文字列置換、列抽出、出力整形などを自動化するSkill。
📜 元の英語説明(参考)
Text processing with sed and awk — find-and-replace, column extraction, reformatting, and stream editing. Use when user mentions "sed", "awk", "text processing", "find and replace in files", "column extraction", "stream editing", "text transformation", "reformat output", or processing text from command-line output.
🇯🇵 日本人クリエイター向け解説
コマンドラインからテキストを効率的に処理し、ファイル内の文字列置換、列抽出、出力整形などを自動化するSkill。
※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-17
- 取得日時
- 2026-05-17
- 同梱ファイル
- 1
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
sed と awk
sed の基本
置換
# 各行で最初に出現する箇所を置換
sed 's/old/new/' file.txt
# 各行で出現するすべての箇所を置換
sed 's/old/new/g' file.txt
# 大文字小文字を区別しない置換 (GNU sed)
sed 's/old/new/gI' file.txt
行の削除
# 5行目を削除
sed '5d' file.txt
# 5行目から10行目を削除
sed '5,10d' file.txt
# 空行を削除
sed '/^$/d' file.txt
# パターンに一致する行を削除
sed '/DEBUG/d' file.txt
挿入、追加、インプレース編集
# 3行目の前に新しい行を挿入
sed '3i\new line here' file.txt
# 3行目の後に新しい行を追加
sed '3a\new line here' file.txt
# GNU sed: ファイルをインプレース編集
sed -i 's/old/new/g' file.txt
# BSD sed (macOS): バックアップ拡張子が必要
sed -i '' 's/old/new/g' file.txt
# 両方: 安全のためにバックアップ拡張子を使用
sed -i.bak 's/old/new/g' file.txt
sed のアドレス指定
sed '3s/old/new/' file.txt # 行番号
sed '3,7s/old/new/' file.txt # 行範囲
sed '/START/,$s/old/new/' file.txt # パターンからファイルの終わりまで
sed '/BEGIN/,/END/s/old/new/' file.txt # 2つのパターンの間
sed '1~2s/old/new/' file.txt # 2行おき (GNUのみ)
sed '/KEEP/!d' file.txt # 否定: 一致する行以外すべて
sed と正規表現
# キャプチャグループと後方参照 (基本正規表現)
sed 's/\(foo\)\(bar\)/\2\1/' file.txt
# 拡張正規表現 (-E フラグ) は括弧のエスケープを不要にします
sed -E 's/(foo)(bar)/\2\1/' file.txt
# 日付の再フォーマット: 2024-01-15 -> 01/15/2024
sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\2\/\3\/\1/' file.txt
# HTMLタグの除去
sed -E 's/<[^>]+>//g' file.html
# 先頭と末尾の空白をトリム
sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//' file.txt
複数のコマンド
# -e またはセミコロンで連結
sed -e 's/foo/bar/' -e 's/baz/qux/' file.txt
sed 's/foo/bar/; s/baz/qux/' file.txt
awk の基本
列の出力
# 2列目を出力 (デフォルトでは空白区切り)
awk '{print $2}' file.txt
# 1列目と3列目を出力
awk '{print $1, $3}' file.txt
# 最後の列を出力
awk '{print $NF}' file.txt
フィールドセパレータ
# CSV: カンマをセパレータとして使用
awk -F',' '{print $2}' data.csv
# コロン区切り (例: /etc/passwd)
awk -F':' '{print $1, $3}' /etc/passwd
# 複数のセパレータ
awk -F'[,;]' '{print $1, $2}' file.txt
# 出力セパレータを設定
awk -F',' -v OFS='\t' '{print $1, $3}' data.csv
組み込み変数
# NR: 現在の行番号; NF: 現在の行のフィールド数
awk '{print NR, NF, $0}' file.txt
# FS/OFS: 入力/出力フィールドセパレータ
awk 'BEGIN{FS=","; OFS="\t"} {print $1, $2}' data.csv
# FILENAME: 現在の入力ファイル
awk '{print FILENAME, NR, $0}' *.txt
awk のパターンとアクション
BEGIN と END ブロック
# ヘッダーとフッター
awk 'BEGIN{print "Name\tScore"} {print $1, $2} END{print "---done---"}' file.txt
# 行数をカウント
awk 'END{print NR, "lines"}' file.txt
条件式
# 3列目が100より大きい行を出力
awk '$3 > 100' file.txt
# パターンマッチ
awk '/ERROR/' file.txt
# 否定マッチ
awk '!/DEBUG/' file.txt
# フィールドマッチによる条件式
awk '$1 == "admin" {print $2}' file.txt
# フィールドに対する正規表現マッチ
awk '$2 ~ /^192\.168/' file.txt
# If-else
awk '{if ($3 > 90) print $1, "pass"; else print $1, "fail"}' file.txt
算術演算
# 列の合計
awk '{sum += $2} END{print sum}' file.txt
# 平均
awk '{sum += $2; n++} END{print sum/n}' file.txt
# 3列目の最大値
awk 'NR==1 || $3 > max {max=$3} END{print max}' file.txt
awk の文字列関数
# 文字列を配列に分割
awk '{split($0, parts, ":"); print parts[1]}' file.txt
# substr (1から始まるインデックス)
awk '{print substr($1, 1, 3)}' file.txt
# gsub: グローバル置換; sub: 最初に出現する箇所のみ
awk '{gsub(/foo/, "bar"); print}' file.txt
# match: パターンを見つけ、RSTART/RLENGTH を介して抽出
awk '{if (match($0, /[0-9]+/)) print substr($0, RSTART, RLENGTH)}' file.txt
# printf による整形出力
awk '{printf "%-20s %10.2f\n", $1, $2}' file.txt
# length, tolower, toupper
awk 'length($0) > 80' file.txt
awk '{print tolower($1)}' file.txt
よくあるレシピ
CSVから列を抽出
# シンプルなCSV
awk -F',' '{print $3}' data.csv
# 引用符付きフィールドを含むCSV -- 複雑なケースには適切なパーサーを使用してください
awk -F'","' '{gsub(/^"|"$/, "", $2); print $2}' data.csv
ログ行の再フォーマット
# Apacheログ: IPとURLを抽出
awk '{print $1, $7}' access.log
# syslogからタイムスタンプとメッセージを抽出
sed -E 's/^([A-Z][a-z]+ [0-9]+ [0-9:]+) [^ ]+ (.+)/\1 | \2/' /var/log/syslog
複数のファイルにわたるパターンの一括置換
# 一致するすべてのファイルで置換
find . -name '*.py' -exec sed -i '' 's/old_func/new_func/g' {} +
# 最初にプレビュー (-i フラグなし)
grep -rl 'old_func' --include='*.py' . | xargs sed 's/old_func/new_func/g' | head -20
フィールドの入れ替え
# 1列目と2列目を入れ替え
awk '{temp=$1; $1=$2; $2=temp; print}' file.txt
# sed のキャプチャグループで入れ替え
sed -E 's/^([^ ]+) ([^ ]+)/\2 \1/' file.txt
重複行の削除
# すべての重複を削除し、順序を保持
awk '!seen[$0]++' file.txt
# 特定の列に基づいて重複を削除
awk '!seen[$2]++' file.txt
列の合計
awk '{s+=$2} END{print s}' file.txt
# CSVから一致する行の合計を計算
awk -F',' '/SALE/ {s+=$4} END{printf "%.2f\n", s}' data.csv
その他のワンライナー
# 2つのマーカー間の行を出力 (排他的)
sed -n '/START/,/END/{/START/d;/END/d;p}' file.txt
# 行をカンマで結合
paste -sd',' file.txt
# すべての行にプレフィックスを追加
sed 's/^/PREFIX: /' file.txt
# 末尾のキャリッジリターンを削除 (dos2unix)
sed 's/\r$//' file.txt
# 引用符間の値を抽出
sed -n 's/.*"\([^"]*\)".*/\1/p' file.txt
# 列から一意の値を抽出し、頻度でソート
awk '{print $1}' file.txt | sort | uniq -c | sort -rn
sed と awk: どちらをいつ使うか
| タスク | 使用 |
|---|---|
| 検索と置換 | sed |
| パターンによる行の削除/フィルタリング | (原文がここで切り詰められています) |
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
sed and awk
sed basics
Substitute
# Replace first occurrence per line
sed 's/old/new/' file.txt
# Replace all occurrences per line
sed 's/old/new/g' file.txt
# Case-insensitive replace (GNU sed)
sed 's/old/new/gI' file.txt
Delete lines
# Delete line 5
sed '5d' file.txt
# Delete lines 5 through 10
sed '5,10d' file.txt
# Delete blank lines
sed '/^$/d' file.txt
# Delete lines matching a pattern
sed '/DEBUG/d' file.txt
Insert, append, and in-place editing
# Insert line before line 3
sed '3i\new line here' file.txt
# Append line after line 3
sed '3a\new line here' file.txt
# GNU sed: edit file in place
sed -i 's/old/new/g' file.txt
# BSD sed (macOS): requires backup extension
sed -i '' 's/old/new/g' file.txt
# Both: use backup extension for safety
sed -i.bak 's/old/new/g' file.txt
sed addresses
sed '3s/old/new/' file.txt # Line number
sed '3,7s/old/new/' file.txt # Line range
sed '/START/,$s/old/new/' file.txt # Pattern to end of file
sed '/BEGIN/,/END/s/old/new/' file.txt # Between two patterns
sed '1~2s/old/new/' file.txt # Every 2nd line (GNU only)
sed '/KEEP/!d' file.txt # Negate: all lines except match
sed with regex
# Capture groups and backreferences (basic regex)
sed 's/\(foo\)\(bar\)/\2\1/' file.txt
# Extended regex (-E flag) avoids escaping parens
sed -E 's/(foo)(bar)/\2\1/' file.txt
# Reformat dates: 2024-01-15 -> 01/15/2024
sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\2\/\3\/\1/' file.txt
# Strip HTML tags
sed -E 's/<[^>]+>//g' file.html
# Trim leading and trailing whitespace
sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//' file.txt
Multiple commands
# Chain with -e or semicolons
sed -e 's/foo/bar/' -e 's/baz/qux/' file.txt
sed 's/foo/bar/; s/baz/qux/' file.txt
awk basics
Print columns
# Print second column (whitespace-separated by default)
awk '{print $2}' file.txt
# Print first and third columns
awk '{print $1, $3}' file.txt
# Print last column
awk '{print $NF}' file.txt
Field separator
# CSV: use comma as separator
awk -F',' '{print $2}' data.csv
# Colon-separated (e.g., /etc/passwd)
awk -F':' '{print $1, $3}' /etc/passwd
# Multiple separators
awk -F'[,;]' '{print $1, $2}' file.txt
# Set output separator
awk -F',' -v OFS='\t' '{print $1, $3}' data.csv
Built-in variables
# NR: current line number; NF: number of fields in current line
awk '{print NR, NF, $0}' file.txt
# FS/OFS: input/output field separators
awk 'BEGIN{FS=","; OFS="\t"} {print $1, $2}' data.csv
# FILENAME: current input file
awk '{print FILENAME, NR, $0}' *.txt
awk patterns and actions
BEGIN and END blocks
# Header and footer
awk 'BEGIN{print "Name\tScore"} {print $1, $2} END{print "---done---"}' file.txt
# Count lines
awk 'END{print NR, "lines"}' file.txt
Conditionals
# Print lines where column 3 > 100
awk '$3 > 100' file.txt
# Pattern match
awk '/ERROR/' file.txt
# Negated match
awk '!/DEBUG/' file.txt
# Conditional with field match
awk '$1 == "admin" {print $2}' file.txt
# Regex match on a field
awk '$2 ~ /^192\.168/' file.txt
# If-else
awk '{if ($3 > 90) print $1, "pass"; else print $1, "fail"}' file.txt
Arithmetic
# Sum a column
awk '{sum += $2} END{print sum}' file.txt
# Average
awk '{sum += $2; n++} END{print sum/n}' file.txt
# Max value in column 3
awk 'NR==1 || $3 > max {max=$3} END{print max}' file.txt
awk string functions
# split string into array
awk '{split($0, parts, ":"); print parts[1]}' file.txt
# substr (1-indexed)
awk '{print substr($1, 1, 3)}' file.txt
# gsub: global substitution; sub: first occurrence only
awk '{gsub(/foo/, "bar"); print}' file.txt
# match: find pattern, then extract via RSTART/RLENGTH
awk '{if (match($0, /[0-9]+/)) print substr($0, RSTART, RLENGTH)}' file.txt
# printf for formatted output
awk '{printf "%-20s %10.2f\n", $1, $2}' file.txt
# length, tolower, toupper
awk 'length($0) > 80' file.txt
awk '{print tolower($1)}' file.txt
Common recipes
Extract column from CSV
# Simple CSV
awk -F',' '{print $3}' data.csv
# CSV with quoted fields -- use a proper parser for complex cases
awk -F'","' '{gsub(/^"|"$/, "", $2); print $2}' data.csv
Reformat log lines
# Apache log: extract IP and URL
awk '{print $1, $7}' access.log
# Extract timestamp and message from syslog
sed -E 's/^([A-Z][a-z]+ [0-9]+ [0-9:]+) [^ ]+ (.+)/\1 | \2/' /var/log/syslog
Bulk rename patterns across files
# Replace in all matching files
find . -name '*.py' -exec sed -i '' 's/old_func/new_func/g' {} +
# Preview first (no -i flag)
grep -rl 'old_func' --include='*.py' . | xargs sed 's/old_func/new_func/g' | head -20
Swap fields
# Swap columns 1 and 2
awk '{temp=$1; $1=$2; $2=temp; print}' file.txt
# Swap with sed capture groups
sed -E 's/^([^ ]+) ([^ ]+)/\2 \1/' file.txt
Remove duplicate lines
# Remove all duplicates, preserving order
awk '!seen[$0]++' file.txt
# Remove duplicates based on a specific column
awk '!seen[$2]++' file.txt
Sum a column
awk '{s+=$2} END{print s}' file.txt
# Sum matching rows from a CSV
awk -F',' '/SALE/ {s+=$4} END{printf "%.2f\n", s}' data.csv
More one-liners
# Print lines between two markers (exclusive)
sed -n '/START/,/END/{/START/d;/END/d;p}' file.txt
# Join lines with commas
paste -sd',' file.txt
# Add a prefix to every line
sed 's/^/PREFIX: /' file.txt
# Remove trailing carriage returns (dos2unix)
sed 's/\r$//' file.txt
# Extract values between quotes
sed -n 's/.*"\([^"]*\)".*/\1/p' file.txt
# Unique values from a column, sorted by frequency
awk '{print $1}' file.txt | sort | uniq -c | sort -rn
sed vs awk: when to use which
| Task | Use |
|---|---|
| Find-and-replace | sed |
| Delete/filter lines by pattern | sed (or grep) |
| In-place file editing | sed |
| Column extraction | awk |
| Arithmetic, aggregation | awk |
| Conditional logic per line | awk |
| Reformatting structured text | awk |
Rule of thumb: if you need columns or math, use awk. If you need search-and-replace or line deletion, use sed.
Gotchas
BSD vs GNU sed
| Feature | GNU sed (Linux) | BSD sed (macOS) |
|---|---|---|
| In-place edit | sed -i 's/.../.../' |
sed -i '' 's/.../.../' |
\t in replacement |
Supported | Not supported (use literal tab) |
| Case-insensitive flag | s/old/new/I |
Not available |
Line stepping 1~2 |
Supported | Not available |
\+, \? in basic regex |
Supported | Not supported (use -E) |
Portable approach: always use -E for extended regex and -i.bak for in-place editing on both platforms.
Quoting in shell
# Use single quotes to prevent shell expansion
sed 's/$HOME/replaced/' file.txt # $HOME is literal
sed "s/$HOME/replaced/" file.txt # $HOME is expanded by shell
# To use shell variables in sed, use double quotes
name="world"
sed "s/hello/$name/" file.txt
# Escape slashes with alternate delimiters
sed 's|/usr/local/bin|/opt/bin|g' file.txt
sed 's#old/path#new/path#g' file.txt
# Pass shell variables to awk with -v
name="admin"
awk -v user="$name" '$1 == user {print $2}' file.txt
# Never embed shell variables directly in awk single-quoted blocks
# This does NOT work:
awk '$1 == "$name"' file.txt # literal string "$name"