Linux: テキストエディタ — nanoの基礎とvimの基本
LinuxサーバーにはVS CodeのGUIはありません。設定ファイルの修正やコードの記述には、ターミナルのテキストエディタに頼るしかありません。最もよく使われる2つはnano(学習コストゼロ)とvim(効率の王様)です。
📋 前提条件:まず以下を完了していること
- レッスン3:ターミナルの基礎
1. このレッスンで学ぶこと
- nanoの基本的な使い方
- vimの3つのモード
- vimのカーソル移動と編集
- vimの検索と置換
- 自分に合ったエディタの選び方
2. ターミナルでファイルを編集するストーリー
(1) 悩み:SSHログイン後にVS Codeが使えない
小明はSSHでサーバーにログインし、Nginxの設定ファイルを編集したかったのですが、サーバーにはVS CodeもGUIもありません。vimは聞いたことがあるものの使い方が分からず — 開いてみても終了の仕方さえ分かりませんでした。
先輩エンジニアのボブが必須キーシーケンスを教えてくれました:iで挿入モードに入り書き始める、Escでノーマルモードに戻る、:wqで保存して終了。
(2) 3ステップ法
ボブは言いました。「この3ステップを覚えれば、vimでどんなファイルでも編集できます。」
iで挿入モードに入り編集開始、Escでノーマルモードに戻る、:wqで保存して終了。この3ステップだけでvimの大部分の編集作業に対応できます。残りは徐々に覚えればよいのです。
vim /etc/nginx/nginx.conf
# 1. Press i to enter insert mode — start editing
# 2. After editing, press Esc to return to normal mode
# 3. Type :wq and press Enter — save and quit
(3) 得られるもの:設定ファイルの編集がもう怖くない
vimの基本を学んだ後、小明はサーバー設定の編集が実は速いことに気づきました — ファイルを開き、変更する行を見つけ、iで修正、:wqで保存。全体で30秒もかかりません。
3. 知識ポイント
(1) nano — ゼロ障壁のエディタ
nanoはすべてのLinuxシステムにプレインストールされているシンプルなエディタです。操作ヒントが画面下部に表示されます。
ℹ️ 注意:たまに設定ファイルを編集するだけなら、nanoは学習コストゼロで十分です。毎日大量にテキストを編集する必要があるなら、vimの方がはるかに効率的です。まずはnanoから始め、nanoでは物足りなくなったらvimに切り替えましょう。
ファイルを開く:
nano filename
nano /etc/nginx/nginx.conf # When sudo is needed: sudo nano /etc/nginx/nginx.conf
よく使うショートカット(^はCtrlキーを意味します):
| ショートカット | 動作 |
|---|---|
Ctrl + O |
ファイルを保存 |
Ctrl + X |
nanoを終了 |
Ctrl + W |
テキストを検索 |
Ctrl + K |
現在の行をカット |
Ctrl + U |
貼り付け |
Ctrl + G |
ヘルプを表示 |
Alt + U |
元に戻す |
Alt + E |
やり直し |
(2) vimの3つのモード
vimの最大の特徴はモード駆動 — 同じキーが異なるモードで異なる機能を持ちます。
┌─────────────────────────────┐
│ Normal Mode │ ← Default mode on startup, for movement and operations
│ Press i / a / o → Insert Mode │
│ Press v / V → Visual Mode │
│ Press : → Command-line Mode │
└──────────────┬──────────────┘
│
┌──────────┴──────────┐
↓ ↓
┌──────────────┐ ┌──────────────┐
│ Insert Mode │ │ Visual Mode │
│ │ │ │
│ Press Esc → │ │ Press Esc → │
│ Back to Normal│ │ Back to Normal│
└──────────────┘ └──────────────┘
(3) vimのカーソル移動(ノーマルモード)
h ← Move left one character
j ↓ Move down one line
k ↑ Move up one line
l → Move right one character
w Jump to the start of the next word
b Jump to the start of the previous word
0 Jump to the beginning of the line
$ Jump to the end of the line
gg Jump to the beginning of the file
G Jump to the end of the file
:line_number Jump to a specific line (e.g., :42 jumps to line 42)
Ctrl+F Scroll down one page
Ctrl+B Scroll up one page
3ddは3行削除、5yyは5行コピー、10jは10行下に移動。これがvimの効率性の鍵の一つ:カウントプレフィックスで繰り返しキー入力を避けます。
(4) vimの編集操作(ノーマルモード)
i Insert before cursor (enter insert mode)
a Insert after cursor
o Open a new line below and enter insert mode
O Open a new line above and enter insert mode
x Delete character under cursor
dd Delete current line
dw Delete a word
d$ Delete to end of line
yy Copy current line (yank)
yw Copy a word
p Paste after cursor
P Paste before cursor
u Undo
Ctrl+R Redo
(5) vimの検索と置換
# Search (normal mode)
/pattern Search forward for pattern
?pattern Search backward for pattern
n Jump to next match
N Jump to previous match
# Replace (command-line mode)
:%s/old/new/g Replace all "old" with "new" in the entire file
:%s/old/new/gc Replace all with confirmation for each match
:5,20s/old/new/g Replace in lines 5-20
(6) ▶ サンプル:nanoでファイルを編集
# Create and edit a file
nano hello.txt
# In nano:
# 1. Type "Hello Linux!"
# 2. Ctrl + O → press Enter to save
# 3. Ctrl + X → exit nano
# View file contents
cat hello.txt
出力:
TEXTHello Linux!
(7) ▶ サンプル:vimの基本操作
# Open a file
vim practice.txt
# Practice sequence:
# 1. Press i → enter insert mode
# 2. Type "This is line 1" → press Enter
# 3. Type "This is line 2"
# 4. Press Esc → return to normal mode
# 5. Type :wq → press Enter to save and quit
(8) ▶ サンプル:vimのコピー&ペースト
# 1. Open a file with vim
vim practice.txt
# 2. yy to copy current line
# 3. p to paste below
# 4. Press p repeatedly to paste multiple times
# 5. 5yy to copy 5 lines
# 5p to paste 5 times
# 6. dd to delete current line
# 7. 3dd to delete 3 lines
(9) ▶ サンプル:vimの検索と置換
vim config.txt
# Search for nginx
/nginx
n # Next match
N # Previous match
# Replace all "port" with "PORT"
:%s/port/PORT/g
# Replace with confirmation
:%s/port/PORT/gc
# Each match will prompt: y confirm / n skip / a all
(10) ▶ サンプル:vimの設定(~/.vimrc)
シンプルな.vimrc設定ファイルを作成してvimを使いやすくしましょう:
cat > ~/.vimrc << 'EOF'
syntax on " Syntax highlighting
set number " Show line numbers
set tabstop=2 " Tab width 2
set shiftwidth=2 " Indent width 2
set expandtab " Use spaces instead of tabs
set autoindent " Auto indent
set cursorline " Highlight current line
set hlsearch " Highlight search results
set ignorecase " Case-insensitive search
set incsearch " Incremental search
EOF
(11) ▶ 総合例:vimでNginx設定ファイルを編集
# Open the Nginx default site configuration
sudo vim /etc/nginx/sites-available/default
# Operation steps:
# 1. /server_name Search for server_name
# 2. n Jump to next occurrence
# 3. i Enter insert mode, modify the domain
# 4. Esc Exit insert mode
# 5. /root Search for root path
# 6. Modify the website root directory
# 7. :wq Save and quit
# 8. sudo nginx -t Test configuration
# 9. sudo systemctl reload nginx Reload configuration
❓ よくある質問
Q: vimの終了方法は(古典的な質問)? A: 順番に:
Esc(ノーマルモードであることを確認)→:(コマンドラインモードに入る)→q(終了)またはq!(保存せず強制終了)またはwq(保存して終了)。
Q: nanoとvim、どちらを学ぶべきですか? A: nanoから始め(障壁ゼロ、下部にヒントあり)、徐々にvimを学ぶ。vimに慣れればはるかに効率的ですが、「たまに設定ファイルを編集する」程度ならnanoで十分です。
Q: vimでの元に戻し(アンドゥ)方法は? A: ノーマルモードで
uを押すと元に戻し、Ctrl + Rでやり直し。uを繰り返し押すと複数の変更を元に戻せます。
Q: vimで行番号を表示するには? A: コマンドラインモードで
:set numberと入力。デフォルトで表示するには、~/.vimrcにset numberを追加。
Q: リモートファイルを編集するより良い方法は? A: VS CodeのRemote - SSH拡張機能で、ローカルのVS Codeでリモートファイルを編集できます。JetBrains Gatewayも同様の機能を提供します。しかし、常にこれらのツールが使えるとは限りません — vimの基本を学ぶのは依然として必須スキルです。
📖 まとめ
- nano:最もシンプル、下部にショートカットヒント、初心者やたまの編集に最適
- vim:3つのモード — ノーマル(移動/操作)/ 挿入(編集)/ コマンドライン(保存/終了/検索)
- vim基本3ステップ:
i挿入 →Esc終了 →:wq保存して終了 - 検索:
/pattern+n次へ /N前へ - 置換:
:%s/old/new/gでグローバル置換 ~/.vimrcを作成してvimを使いやすく(行番号/シンタックスハイライト/検索ハイライト)
📝 練習問題
- 基本(難易度 ⭐):nanoで
hello.txtを作成・編集し、3行のテキストを書いて保存・終了し、同じファイルをvimで開いてカーソル移動(h/j/k/l/w/b/gg/G)を練習する - 中級(難易度 ⭐⭐):vimで現在の行をコピー(yy)し5回貼り付け(p)、ファイル内の単語を検索して
n/Nでジャンプし、最後に:%s/old/new/gで置換を実行する - 上級(難易度 ⭐⭐⭐):
~/.vimrc設定ファイルを作成(シンタックスハイライト+行番号+Tab幅2+検索ハイライト)し、vimで/etc/ssh/sshd_configを編集(sudoが必要)、検索と置換操作を練習する