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?

More than 3 years have passed since last update.

【Linux小ネタ】teeコマンドとリダイレクト〜標準入出力、パイプ〜

Posted at

前提条件

OS
MacOS Monterey 12.0.1
CPU
Apple M1(arm64)
Docker
Docker Desktop 4.2.0 (70708)
CentOS
CentOS Linux release 7.9.2009 (AltArch)

この記事の内容

ほんの備忘録です。
実行結果を画面とファイルに出力する「tee」コマンドと、標準入出力を変える「リダイレクト」を、同じ状況で検証・比較するものです。

DockerでCentOS環境を構築し、Linuxコマンドの基礎勉強をやっています。
下記参考文献にある教科書で練習をしていて、簡単にまとめたかったので記事にしました。

やりたいこと

単語の羅列であるファイルの中から「app」を含む部分(大文字・小文字の別は不問)を検索し、その結果を新しいファイルに出力する

手順

まず、実験用のファイルを作ります。内容はこんな感じ。

[Qiita@0a412e1af0a1 ~]$ cat bunsyo1.txt
sam
101
Apple
samp21
APPLE
apple
Linux
test
PINEAPPLE

1 リダイレクトを使う場合

[Qiita@0a412e1af0a1 ~]$ grep -i app bunsyo1.txt > apple.txt

大文字・小文字を区別せず検索するため、grepにはiオプションをつけます。

> apple.txt
標準出力を、ディスプレイからファイルに切り替えます。
(ここでは出力するファイルとして「apple.txt」を新規作成します。)

出力されたファイルの中身を確かめます。

[Qiita@0a412e1af0a1 ~]$ cat apple.txt
Apple
APPLE
apple
PINEAPPLE

(ちなみに・・・)

[Qiita@0a412e1af0a1 ~]$ grep -i app bunsyo1.txt > apple.txt | cat apple.txt
[Qiita@0a412e1af0a1 ~]$ 

| cat apple.txt
パイプの後にcatを記述しても画面出力はされません。
リダイレクトで出力先をディスプレイでなくファイルとしているので、当然といえば当然ですね笑
すいませんでした()

2 teeコマンドとパイプを使う場合

一旦、rmコマンドで出力されたapple.txtを削除してから試してみます。

[Qiita@0a412e1af0a1 ~]$ grep -i app bunsyo1.txt | tee apple.txt 
Apple
APPLE
apple
PINEAPPLE

出力されたファイルの中身自体は同じ結果となります。

teeコマンドは、実行結果を「画面」と「ファイル」に出力してくれます。

(公式マニュアル記載 抜粋)
The tee utility shall copy standard input to standard output, making a copy in zero or more files.

・標準入力(キーボードから入力されたコマンドの実行結果)の内容を標準出力(ディスプレイ)にコピーする
・コピーは別ファイルに作成することもできる(今回でいうapple.txt)

といった趣旨のことが書いてありますね。

参考文献

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?