パイプとリダイレクトの基礎
パイプとリダイレクトの基礎
Section titled “パイプとリダイレクトの基礎”パイプとリダイレクトは、Linuxコマンドを組み合わせて強力な処理を行うための重要な機能です。
リダイレクト
Section titled “リダイレクト”標準出力のリダイレクト
Section titled “標準出力のリダイレクト”# 標準出力をファイルに書き込む(上書き)ls > file_list.txt
# 標準出力をファイルに追記ls >> file_list.txt
# 標準エラーをファイルに書き込むcommand 2> error.log
# 標準出力と標準エラーを同じファイルにcommand > output.log 2>&1
# 標準出力と標準エラーを別々のファイルにcommand > output.log 2> error.log標準入力のリダイレクト
Section titled “標準入力のリダイレクト”# ファイルから標準入力に読み込むcommand < input.txt
# ヒアドキュメントcommand << EOFline1line2EOF# コマンドの出力をファイルに保存ps aux > processes.txt
# エラーログを別ファイルに保存python app.py > output.log 2> error.log
# すべての出力を同じファイルにpython app.py > all.log 2>&1
# ファイルの内容をコマンドに渡すsort < unsorted.txt > sorted.txt基本的な使い方
Section titled “基本的な使い方”# コマンドの出力を次のコマンドの入力にcommand1 | command2
# 複数のパイプを連結command1 | command2 | command3# プロセス一覧から特定のプロセスを検索ps aux | grep nginx
# ログファイルからエラーを検索して表示cat /var/log/app.log | grep ERROR | tail -20
# ファイル一覧をソートして表示ls -l | sort
# 重複を除去cat file.txt | sort | uniq
# 行数をカウントcat file.txt | wc -l
# 大きなファイルの最初の100行を表示cat large_file.txt | head -100よく使うパイプの組み合わせ
Section titled “よく使うパイプの組み合わせ”1. grepとパイプ
Section titled “1. grepとパイプ”# ログからエラーを検索cat /var/log/app.log | grep ERROR
# 複数の条件で検索ps aux | grep -E "nginx|apache"
# 検索結果の前後を表示cat /var/log/app.log | grep -A 5 -B 5 ERROR2. sortとuniq
Section titled “2. sortとuniq”# ファイルをソートcat file.txt | sort
# 重複を除去cat file.txt | sort | uniq
# 重複行の数をカウントcat file.txt | sort | uniq -c
# 重複行のみを表示cat file.txt | sort | uniq -d3. awkとsed
Section titled “3. awkとsed”# awk: テキスト処理ps aux | awk '{print $2, $11}' # PIDとコマンド名を表示
# sed: テキスト置換cat file.txt | sed 's/old/new/g'
# 特定の行を抽出cat file.txt | sed -n '10,20p' # 10-20行目を表示4. cutとtr
Section titled “4. cutとtr”# cut: フィールドの抽出echo "a,b,c,d" | cut -d',' -f1,3 # a,c
# tr: 文字の変換・削除echo "HELLO" | tr 'A-Z' 'a-z' # helloecho "hello world" | tr -d ' ' # helloworld高度なパイプの使い方
Section titled “高度なパイプの使い方”xargs(引数の展開)
Section titled “xargs(引数の展開)”# ファイル一覧に対してコマンドを実行find . -name "*.txt" | xargs rm
# 並列実行(-P: parallel)find . -name "*.txt" | xargs -P 4 -I {} process_file {}
# 引数の最大数を指定(-n: max-args)find . -name "*.txt" | xargs -n 1 echotee(出力の分岐)
Section titled “tee(出力の分岐)”# 標準出力をファイルにも書き込むcommand | tee output.log
# 追記モードcommand | tee -a output.log
# 複数のファイルに書き込むcommand | tee file1.log file2.log# コマンドの実行結果をファイルに保存しながら表示ps aux | tee processes.txt | grep nginx
# ログをファイルに保存しながらリアルタイムで表示tail -f /var/log/app.log | tee app_backup.log | grep ERRORパイプとリダイレクトのポイント:
- リダイレクト:
>(上書き)、>>(追記)、2>(標準エラー) - パイプ:
|でコマンドを連結 - よく使う組み合わせ: grep、sort、uniq、awk、sed
- xargs: 引数の展開、並列実行
- tee: 出力の分岐、ファイルへの保存
適切にパイプとリダイレクトを使用することで、強力な処理ができます。