0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

パイプ・リダイレクトと正規表現

Last updated at Posted at 2025-10-13

『Linux標準教科書』を読み始めながら、学びを自分の言葉で整理した忘備録です。
標準教科書の内容についてChatGPTの対話で得た理解・補足をかみ砕いてまとめました。

本記事は全12章のうちの第4章。正規表現・パイプ・リダイレクトについて、標準教科書を軸にしながらChatGPTとの会話を肉付けしていく形で整理したものになります。
学ぶ途中のつまずきや疑問もそのまま残す方針なので、同じところで悩む人の助けになればと思ってます!
3章と5章のまとめも併せてご確認ください!

目次

入出力

  • Linux(というよりUNIX系のプロセス)には1つの入口(標準入力=stdin, FD 0)と2つの出口(標準出力=stdout, 標準エラー出力=stderr)がある

リダイレクト

  • >標準出力を上書きでファイルに保存、>>追記
  • 1> は標準出力、2> は標準エラーを明示
  • 2>&1標準エラー(2)を標準出力(1)と同じ行き先に合流させる(順序が重要)

基本:上書きと追記

$ echo "first" > out.txt
$ echo "second" >> out.txt
$ cat out.txt
first
second

標準エラーだけをファイルへ

$ ls /no/such/path 2> err.log
$ cat err.log
ls: cannot access '/no/such/path': No such file or directory

標準出力と標準エラーを同じファイルへ(順序に注意)

$ cmd > all.log 2>&1

対話入力でファイルを作る(catはエディタではない)

$ cat > memo.txt
line1
line2
# Ctrl-D で終了(EOF)
$ cat memo.txt
line1
line2

パイプ

  • |左コマンドの標準出力右コマンドの標準入力へ渡す
  • ログの濾過、集計、形式変換で多用する

想定例:ファイル数を数える

$ ls -1 | wc -l
12

想定例:エラーも含めて後段へ渡したい

$ cmd 2>&1 | grep -i error
# stdout/stderr 合流後に grep

grepの使い方

  • 形式:grep [オプション] パターン [ファイル ...]
  • ディレクトリを渡すとエラー。下位ディレクトリも検索したいときは -r / -R
    • /etc/*を渡すと、grep: /etc/systemd: Is a directoryというエラーがディレクトリ数出力される

正規表現の基本

  • ^行頭^abcはabcから始まるファイル
  • $行末abc$はabcで終わるファイル
  • .任意の1文字
  • [abc]a/b/c のいずれか1文字
  • [^abc]a/b/c 以外の1文字
  • \ はメタ文字のエスケープ(日本語配列で「¥」表示でも実体はバックスラッシュ \
  • 補足:grep は既定で 基本正規表現(BRE)grep -E拡張正規表現(ERE)+? を素直に使いたい場合に便利)

主なオプション例

  • -i 大文字小文字を無視
  • -e 文字列を検索対象にする
  • -n 行番号を表示
  • -r-R)ディレクトリを再帰検索
  • -w 単語として一致
  • -v 不一致行を表示
  • --color=auto マッチ箇所を色付け
  • --include="*.conf" / --exclude-dir=".git"(再帰時の絞り込み)

実例いろいろ

例1:行頭が Listen の行のみ(設定ファイルでありがち)

$ grep -n '^Listen' /etc/httpd/conf/httpd.conf
42:Listen 80

例2:現在ディレクトリ配下の .conftimeout を大小無視検索

$ grep -ri --include="*.conf" -n 'timeout' .
./nginx/nginx.conf:17:proxy_read_timeout 60s;

例3:エラーログから ERROR を含まない行だけを抽出

$ grep -v 'ERROR' app.log | head
# 想定出力:ERROR を含まない最初の10行

例4:ディレクトリを渡すとエラー(stderr)→ -r で解決

$ grep 'root' /etc
grep: /etc: Is a directory # grep 'root' /etc/* などにすると、/etc下のディレクトリ数分、このエラーが出力
$ grep -r 'root' /etc | head
/etc/passwd:0:root:x:0:0:root:/root:/bin/bash
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?