8
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Linuxコマンド「rm -rf」「cp」「mv」「head」「tail」「tail -f」「less」「grep」

Posted at

Linux使い始めの人だとあまり知らなさそうな「ファイル・ディレクトリ操作」「ファイル内容の確認」に関するコマンドをまとめてみました。

目次

ファイル・ディレクトリ操作

-rm -rf
-cp
-mv

ファイル内容の確認

-head
-tail
-tail -f
-less
-grep

ファイル・ディレクトリ操作

rm -rf ディレクトリ名

ディレクトリを中身ごと削除


cp コピー元 コピー先

ファイルコピー


mv X Y

ファイルやディレクトリの移動orリネーム。
Y最後尾に「/」があれば、XをYに移動。XとYの両方の最後尾に「/」がなければXをYにリネーム。

# app.rbファイルをsrcディレクトリに移動
mv app.rb src/

# projectディレクトリをworkspaceディレクトリに移動
mv project/ workspace/

# 複数ファイルを一度に移動
mv file1.txt file2.txt documents/

# old_folderをnew_folderにリネーム
mv old_folder new_folder

# old_coin.rbをnew_coin.rbにリネーム
mv old_coin.rb new_coin.rb

ファイル内容の確認

head ファイル名

ファイルの先頭10行を表示


tail ファイル名

ファイルの末尾10行を表示


tail -f ファイル名

リアルタイムでログを監視
ログファイルを監視したいときに使う

# 下記のように実行することで、複数のログファイルを同時に監視することも可能です。
tail -f log/development.log log/sidekiq.log log/error.log

less ファイル名

ページ単位でファイル内容を表示

<catコマンドとの違い>
catコマンド・・・ファイル全体を表示。短いファイルを見たい場合に適している。

lessコマンド・・・ファイルの一定の長さ分が表示される。前後へ動かしたり、文字列検索したりして見ていく。長いファイル(ログファイルや設定ファイル)を見たい場合に適している。


grepコマンド

# ファイル内から文字列を検索
grep "文字列" ファイル名

# 大文字小文字を区別しない検索
grep -i "文字列" ファイル名

# 結果を行番号と一緒に出力
grep -n "文字列" ファイル名

# 文字列にマッチしない行を表示(使用場面例:コメント行を除いて内容を表示したいとき。テストデータを除いて本番データだけを表示したいとき。)
grep -v "文字列" ファイル名

# 指定した文字列が含まれる、指定した拡張子のファイルを検索
grep "文字列" *.拡張子

# 現在のディレクトリ以下のすべてのファイルから、指定した文字列が含まれる行を検索
grep -r "文字列" ./

以上

8
2
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
8
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?