Skip to main content

Command Palette

Search for a command to run...

Linux Text File & Editor: Vim

Published
31 min read
Linux Text File & Editor: Vim

1️⃣ Text File
2️⃣ Use a Text Editor


1️⃣ Text File

Linux and Unix: Are They the Same?

Linux and Unix are not completely identical, but they can be considered very similar from a user's perspective. Looking at their internal structure, there are real differences, and there is also the distinction that Unix is paid while Linux is free. However, since they are not significantly different in terms of actual usage, learning how to use Linux will allow you to adapt to a Unix environment without much difficulty.

In this session, we will look at how to edit text files in a Linux environment.

텍스트 파일 편집: 리눅스와 유닉스는 같은가?

리눅스와 유닉스는 완전히 동일하지는 않지만, 사용자 관점에서는 매우 유사하다고 할 수 있다. 내부 구조를 들여다보면 실질적인 차이가 존재하고, 유닉스가 유료인 반면 리눅스는 무료라는 차이점도 있다. 하지만 실제 사용법 측면에서는 크게 다르지 않기 때문에, 리눅스를 중심으로 운영체제 사용법을 익혀두면 유닉스 환경에서도 무리 없이 적응할 수 있다.

이번 시간에는 실제 리눅스 환경에서 텍스트 파일을 어떻게 편집하는지 살펴본다.


What is a Text File?

The most familiar example of a text file is the .txt file. By definition, a text file is a file that stores electronically represented characters arranged in sequence.

The difference becomes clear when compared to a PPT file. PPT requires a specific company's editor which is PowerPoint - to open it, whereas text files are not tied to any specific format. There is a dedicated viewer for text files called a text editor, but since it comes pre-installed on computers at no additional cost, it is referred to as a basic editor.

So why is this basic editor necessary? The simplest reason is that it is needed for handling program inputs and modifying various system settings. Since text files are stored in a human-readable format, opening one in an editor lets you see characters like A, B, and C directly.

Early computers were developed around the alphabet, so non-alphabetic characters like Korean were not supported. Today, however, the underlying structure has evolved to support a wide range of languages.

텍스트 파일이란?

텍스트 파일은 평소에 익숙하게 접해온 .txt 파일이 대표적인 예다. 정의하자면, 전자적인 문자가 나열된 형태로 저장된 파일을 텍스트 파일이라고 한다.

PPT 파일과 비교하면 차이가 명확해진다. PPT는 파워포인트라는 특정 회사의 편집기가 있어야만 열람이 가능한 반면, 텍스트 파일은 특정 형식에 종속되지 않는다. 텍스트 파일을 열기 위한 전용 뷰어, 즉 텍스트 편집기가 존재하지만, 추가 비용 없이 컴퓨터에 기본으로 설치되어 있기 때문에 '기본 편집기'라고 부른다.

그렇다면 이 기본 편집기는 왜 필요할까? 가장 간단한 이유는 프로그램의 입력값을 다루거나 각종 설정을 변경할 때 필요하기 때문이다. 텍스트 파일은 사람이 읽기 쉬운 형식으로 되어 있어, 편집기로 열면 A, B, C와 같은 문자를 그대로 확인할 수 있다.

초기 컴퓨터는 알파벳 중심으로 발전해왔기 때문에 한국어와 같은 비알파벳 문자는 지원되지 않았다. 그러나 현재는 기본 구조 수준에서 다양한 언어를 지원할 수 있도록 발전하였다.


How to Check a Text File

To check whether a file is in text format, use the file command.

file ~/.profile

This will return something like .profile: ASCII text, confirming it is a text file. On the other hand,

file /usr/bin/ls

returns something like ELF 64-bit LSB pie executable .... This is an executable file, commonly referred to as a binary file. A binary file is represented in binary and is formatted for computers to process rather than for humans to read.

텍스트 파일 확인 방법

현재 다루는 파일이 텍스트 형식인지 확인하려면 file 명령어를 사용한다.

file ~/.profile

위 명령어를 입력하면 .profile: ASCII text와 같이 텍스트 형식임을 알려준다. 반면,

file /usr/bin/ls

를 입력하면 ELF 64-bit LSB pie executable ...과 같은 결과가 출력된다. 이는 실행 가능한 파일로, 통상 바이너리 파일이라고 부른다. 바이너리 파일은 이진수로 표현된 파일로, 사람이 읽기보다는 컴퓨터가 처리하기에 적합한 형식이다.


ASCII and Encoding

As mentioned earlier, Korean was added to computers later, which relates to ASCII - the early character encoding system. ASCII is composed of 7 bits and divides characters into two categories:

  • Printable characters: 32 ~ 126

  • Control characters (non-printable): 0 ~ 31, 127

Computers recognize everything as numbers. For example, uppercase A is stored as 65 and lowercase a as 97. These numbers are converted into human-readable characters according to ASCII-based encoding and decoding rules. Both 65 and 97 fall within the printable character range.

ASCII와 인코딩

한글은 컴퓨터에 나중에 적용되었다고 언급했는데, 이는 초기 컴퓨터 문자 체계인 ASCII와 관련이 있다. ASCII는 7비트로 구성되며, 문자는 크게 두 종류로 나뉜다.

  • 출력 가능한 문자: 32 ~ 126

  • 제어 문자 (출력되지 않는 문자): 0 ~ 31, 127

컴퓨터는 모든 것을 숫자로 인식한다. 예를 들어 대문자 A는 65, 소문자 a는 97로 저장되며, ASCII 기반의 인코딩·디코딩 규칙에 따라 이 숫자들이 사람이 읽을 수 있는 문자로 변환된다. 65와 97은 모두 출력 가능한 문자 범위에 해당한다.


Viewing File Contents: head

head is a command that outputs the beginning (head) of a file. It is used when you only want to check the first part of a text file that is organized line by line.

The reason for viewing only the beginning goes back to the limitations of early monitors. While modern monitors can display large amounts of text on a single screen, early monitors could only display around 40–80 characters wide and about 20 lines tall. Before that, there were no screens at all — punch card devices were used to output one line at a time. Because what could be shown on screen was so limited, and like a TV where content that has scrolled past cannot be seen again, commands were needed to view just a portion of a file.

Usage: head ~/.profile outputs the default 10 lines, and head -n 7 ~/.profile outputs only 7 lines using the -n option. The -n can be omitted and it will work the same way.

head는 파일의 앞부분(머리 부분)을 출력하는 명령어다. 텍스트 파일은 문자들이 줄 단위로 구성되어 있는데, 그 중 앞부분만 확인하고 싶을 때 사용한다.

굳이 앞부분만 보는 이유는 초기 모니터의 한계에서 비롯된다. 현재의 모니터는 많은 양의 텍스트를 한 화면에 표시할 수 있지만, 초기 모니터는 가로 40~80자, 세로 20줄 내외만 표현 가능했다. 그 이전에는 화면 자체가 없었고 펀치카드 장치로 한 줄씩 출력하는 방식을 사용했다. 이처럼 한 화면에 표시할 수 있는 내용이 제한적이었기 때문에, TV 화면처럼 한번 지나간 내용은 다시 볼 수 없는 환경에서 파일의 일부분만 확인하기 위한 명령어가 필요했다.

사용법은 다음과 같다.

head ~/.profile을 입력하면 기본값인 10줄이 출력되며, head -n 7 ~/.profile과 같이 -n 옵션으로 출력할 줄 수를 직접 지정할 수도 있다. -n은 생략해도 동일하게 동작한다.


Viewing File Contents: tail

tail is the counterpart to head - just like the relationship between a head and a tail, it outputs the end of a file. Entering tail -n 7 ~/.profile outputs the last 7 lines of the file. The usage is the same as head, but the result is different. In summary, head outputs from the beginning and tail outputs from the end.

Note that depending on the user's environment, the .profile file may not exist or its contents may differ. If the file has not been modified from its initial state, the results from head and tail may look nearly the same, but if changes have been made, the results will differ.

텍스트 파일 내용 보기: tail

tailhead와 상응하는 명령어로, 머리와 꼬리의 관계처럼 파일의 뒷부분을 출력한다. tail -n 7 ~/.profile을 입력하면 파일의 마지막 7줄을 출력한다는 점에서 head와 사용법은 같지만 결과는 다르다. 정리하자면 head는 앞에서부터, tail은 뒤에서부터 지정한 줄 수만큼 출력한다고 이해하면 된다.

단, 사용자 환경에 따라 .profile 파일이 없거나 내용이 다를 수 있다. 초기 설정 그대로라면 headtail의 결과가 거의 동일하게 보일 수 있지만, 중간에 내용을 수정했다면 결과에 차이가 생긴다.


The Meaning of ~

Why do we use ~ in commands? The ~ symbol represents the home directory of the currently logged-in user. It is both a relative and absolute reference. In most cases, users continue with the account they initially logged in with, but administrators can switch to another user without logging out. In that case, ~ points to the home directory of the switched user. In other words, ~ always refers to the home directory of the currently active user.

~의 의미

명령어에서 ~를 사용하는 이유는 무엇일까? ~는 현재 로그인한 사용자의 홈 디렉토리를 의미한다. 상대적인 표시이면서도 절대적인 위치를 가리킨다는 특징이 있다. 대부분의 경우 처음 로그인한 계정을 계속 사용하지만, 관리자는 로그아웃 없이도 다른 사용자로 전환할 수 있다. 이 경우 ~는 전환된 사용자의 홈 디렉토리를 가리키게 된다. 즉, ~는 항상 현재 활성화된 사용자의 홈 디렉토리를 의미한다.


Viewing File Contents: cat

cat stands for "concatenate files and print on the standard output." It is a command that joins files together and outputs their contents to the standard output device.

What is the standard output device? In modern terms, it is natural to think of a monitor, but this has not always been the case. In the early days of computing, the standard output device was paper — a printer. Therefore, saying "output to the monitor" is specific to a particular situation. The more accurate expression is "output to the standard output device." More details on standard output will be covered later.

Usage: entering cat ~/.profile outputs the entire contents of that file to the standard output device. In a typical environment, this will appear on the monitor.

텍스트 파일 내용 보기: cat

cat은 "concatenate files and print on the standard output" 파일을 이어 붙여 표준 출력장치로 내용을 출력하는 명령어다.

여기서 표준 출력장치란 무엇일까? 현재 기준으로는 모니터라고 생각하면 자연스럽지만, 이것이 항상 당연한 것은 아니다. 컴퓨터 초창기에는 표준 출력장치가 모니터가 아닌 종이, 즉 프린터였다. 따라서 "모니터에 출력된다"는 표현은 특정 상황에 한정된 표현이며, 보다 정확하게는 "표준 출력장치로 출력된다"고 하는 것이 맞다. 표준 출력에 대한 자세한 내용은 이후에 다룰 예정이다.

사용법은 다음과 같다. cat ~/.profile을 입력하면 해당 파일의 전체 내용이 표준 출력장치로 출력된다. 일반적인 환경에서는 모니터에 출력되는 것을 확인할 수 있다.


Viewing File Contents: more

more is a command that displays file contents divided according to the terminal screen size. Unlike cat, which outputs everything at once, more shows only as much as the current screen can display.

Running more ~/.profile shows --More-- (32%) at the bottom of the screen, meaning 32% of the total document is currently displayed. The amount shown varies depending on the terminal window size — whether it shows 24 lines or 50 lines depends on the current screen. Since it allows you to read through the entire content in order rather than cutting off a portion like head or tail, it is more useful when you actually want to read a file.

텍스트 파일 내용 보기: more

Display the contents of a file in a terminal

more는 파일의 내용을 터미널 화면 크기에 맞춰 나눠서 출력하는 명령어다. cat처럼 파일 전체를 한꺼번에 출력하는 것이 아니라, 현재 화면에 표시할 수 있는 만큼만 보여준다.

more ~/.profile을 실행하면 화면 하단에 --More-- (32%)와 같은 표시가 나타나는데, 이는 전체 문서 중 32%가 현재 화면에 표시되었다는 의미다. 화면 크기는 사용자마다 다를 수 있어 24줄짜리 화면이든 50줄짜리 화면이든 현재 터미널 창의 크기에 따라 표시되는 양이 달라진다. headtail처럼 일부만 잘라서 보는 것이 아니라 전체 내용을 순서대로 읽어나갈 수 있기 때문에, 파일 내용을 실제로 읽어볼 때 더 유용한 명령어다.


Viewing File Contents: less

Despite its name, less has more features than more. While more only allows forward navigation, less allows you to move both forward and backward freely. Like the scrollbar on the right side of a web browser, less lets you scroll up and down through the file content, making it more convenient for reading long files.

To exit less, press q.

텍스트 파일 내용 보기: less

less는 이름과 달리 more보다 기능이 많은 명령어다. more가 앞으로만 이동 가능한 반면, less는 앞뒤로 자유롭게 이동할 수 있다. 웹 브라우저 오른쪽의 스크롤 바처럼 파일 내용을 위아래로 자유롭게 탐색할 수 있어 긴 파일을 읽을 때 더욱 편리하다.


Using cat with << (Here Document)

In addition to standalone use, cat can be used together with the << operator. << is called the here document operator and allows you to input multiple lines of text at once.

Usage: type cat << end and press Enter, then input the desired content line by line. When finished, type end on the last line and press Enter to terminate input.

cat<< (Here Document) 활용

cat은 단독으로 사용하는 것 외에도 << 연산자와 함께 복합적으로 활용할 수 있다. <<는 here document 연산자라고 부르며, 여러 줄의 텍스트를 한 번에 입력할 수 있게 해준다.

사용법은 다음과 같다. cat << end를 입력하고 엔터를 누른 뒤, 원하는 내용을 한 줄씩 입력한다. 입력이 끝나면 마지막 줄에 end를 입력하고 엔터를 누르면 입력이 종료된다.


Using cat, <<, and > Together

Adding > (redirect output) to the here document operator << allows you to save the input content to a file.

The > is the redirect output operator, meaning send the output to the specified file instead of the monitor. So > new.txt means save the input content to a file named new.txt. By using cat, <<, and > together, you can easily create a text file.

cat, <<, >를 함께 활용하기

앞서 살펴본 here document 연산자 <<>(redirect output)를 추가하면 입력한 내용을 파일로 저장할 수 있다.

여기서 >는 redirect output 연산자로, 출력 결과를 모니터 대신 지정한 파일로 보내라는 의미다. 즉 > new.txt는 입력한 내용을 new.txt라는 이름의 텍스트 파일로 저장하라는 뜻이 된다. 이처럼 cat, <<, >를 함께 사용하면 간단하게 텍스트 파일을 생성할 수 있다.


Using echo with > and >>

echo is a command that outputs the text you type. When used with >, it saves the content to a file.

Here, > overwrites any existing file content. In contrast, >> appends to the existing content. If > is used instead of >>, the existing sample-text would be gone and only another-line would remain. In summary, > means overwrite and >> means append. One thing to note: if >> is used when there is no existing content, since there is nothing to append to, a new file will be created with the input as the first line.

echo>, >> 활용

echo는 입력한 텍스트를 출력하는 명령어로, >와 함께 사용하면 내용을 파일로 저장할 수 있다.

여기서 >는 기존 파일 내용을 덮어쓴다. 반면 >>는 기존 내용에 이어붙이는 역할을 한다. 만약 >>대신 >를 사용했다면 기존의 sample-text는 사라지고 another-line만 출력된다. 정리하자면 >는 덮어쓰기, >>는 이어붙이기라고 이해하면 된다. 한 가지 주의할 점은, 아무 내용도 없는 상태에서 >>를 사용하면 이어붙일 내용이 없으므로 새 파일이 생성되며 입력한 내용이 첫 줄로 저장될 것이다.


Editing Text Files: sed

Once a file is created, editing becomes necessary. As content grows, it is not practical to recreate the file every time a single character needs to be fixed. This is where sed comes in, defined as "stream editor for filtering and transforming text."

cat sample.txt | sed 's/-/*/'

The meaning of 's/-/*/' is as follows: s stands for substitute, meaning replace - with *. Running the command outputs the following:

sample*text
another*line

Importantly, the original file is not changed. Running cat sample.txt again still outputs sample-text and another-line. The result of sed is only shown on the standard output device and is not applied to the original file.

텍스트 파일 편집: sed

파일을 만들었다면 이제 편집이 필요하다. 내용이 많아질수록 한 글자 때문에 파일을 매번 새로 만들 수는 없기 때문이다. 이때 사용하는 것이 sed로, "stream editor for filtering and transforming text"로 정의된다. 즉 텍스트를 걸러내고 변환하는 스트림 편집기다.

여기서 's/-/*/'의 의미는 다음과 같다. s는 substitute(치환)를 뜻하며, -*로 바꾸라는 의미다. 위 명령어를 실행하면 결과는 아래와 같이 출력된다.

sample*text
another*line

단, 중요한 점은 원본 파일은 변경되지 않는다는 것이다. cat sample.txt를 다시 실행하면 여전히 sample-text, another-line으로 출력된다. sed의 결과는 표준 출력장치에 보여지기만 할 뿐, 원본 파일에 적용되지 않기 때문이다.


Saving to a File: tee

To save the result of sed to a file, use the tee command. tee is defined as "read from standard input and write to standard output and files," meaning it can simultaneously write to both the standard output device and a file. In other words, the result is displayed on screen and saved to a file at the same time — two benefits in one.

Running cat sample.txt outputs sample-text and another-line. Piping this to tee smpl.txt displays the same content on screen while also saving it to a new file called smpl.txt. Running cat smpl.txt afterward will show the same result as cat sample.txt.

파일로 저장하기: tee

sed의 결과를 파일에 저장하려면 tee 명령어를 활용한다. tee는 "read from standard input and write to standard output and files"로 정의되며, 표준 입력에서 읽어온 내용을 표준 출력장치와 파일 양쪽에 동시에 쓸 수 있다. 즉, 화면에도 결과가 출력되면서 파일에도 저장되는 일석이조의 명령어다.

cat sample.txt를 실행하면 sample-text, another-line이 출력된다. 여기에 tee smpl.txt를 연결하면 같은 내용이 화면에 출력됨과 동시에 smpl.txt라는 새 파일에도 저장된다. 이후 cat smpl.txt를 실행하면 sample.txt의 결과와 동일하게 sample-text, another-line이 출력되는 것을 확인할 수 있다.


2️⃣ Use a Text Editor

Installing vim

Before installing vim, the package list needs to be updated. When Ubuntu was first installed, it may have only known about version 1.0, but version 1.5 with bug fixes may have since been released. Running sudo apt update refreshes the package list to its latest state. Then install vim with sudo apt install vim, and check the installed version by running vim --version.

vim 설치

vim을 설치하기 전에 먼저 패키지 목록을 최신화해야 한다. 우분투를 처음 설치했을 때는 1.0 버전만 알고 있었더라도, 이후 버그 패치 등을 거쳐 1.5 버전이 출시되었을 수 있기 때문이다. sudo apt update를 실행하면 패키지 목록이 최신 상태로 갱신된다. 이후 sudo apt install vim으로 vim을 설치하고, vim --version을 입력하면 현재 설치된 vim의 버전을 확인할 수 있다.


The vim Launch Screen

Type vi or vim at the prompt and press Enter to launch the editor. On the launch screen, each line begins with a ~ symbol — but be careful here. The ~ used in file paths means the current user's home directory, while the ~ at the start of each line in the vim screen means an empty line with no content. They look the same but mean completely different things, so be careful not to confuse them.

The numbers displayed on the right side of the screen indicate the current cursor position, representing the line (row) and column. In the center of the screen, a brief explanation and manual for using vim is displayed.

vim 실행 화면

프롬프트에서 vi 또는 vim을 입력하고 엔터를 누르면 편집기 화면이 실행된다. 실행 화면에서 각 줄 맨 앞에 ~ 표시가 보이는데, 여기서 주의할 점이 있다. 경로에서 사용하는 ~는 현재 사용자의 홈 디렉토리를 의미하지만, vim 화면에서 줄 맨 앞에 표시되는 ~는 아무 내용도 없는 빈 줄을 의미한다. 같은 모양이지만 전혀 다른 의미이므로 혼동하지 않도록 주의해야 한다.

화면 오른쪽에 표시되는 숫자는 현재 커서의 위치를 나타내며, 줄(row, line)과 칸(column)을 의미한다. 화면 가운데에는 vim 사용 시 참고할 수 있는 간단한 설명과 매뉴얼이 표시된다.


vim's Two Modes

vim is divided into two main modes. One is INSERT mode, where you can directly type text or program code, indicated by -- INSERT -- at the bottom of the screen. The other is NORMAL mode, where instead of typing, you navigate - moving the cursor and finding specific locations.

When first encountering vim, this mode concept can be very confusing. Pressing keys does not type characters; the cursor just moves. However, this mode distinction is actually one of vim's strengths.

vim의 두 가지 모드

vim은 크게 두 가지 모드로 구분된다. 하나는 INSERT 모드로, 텍스트나 프로그램 코드를 직접 입력할 수 있는 상태다. 화면 하단에 -- INSERT --라고 표시된다. 다른 하나는 NORMAL 모드로, 텍스트를 입력하는 것이 아니라 커서를 이동하거나 원하는 위치를 찾는 등의 탐색을 하는 상태다.

처음 vim을 접하면 이 모드 개념이 굉장히 혼란스럽게 느껴진다. 키보드를 눌러도 글자가 입력되지 않고 커서만 움직이기 때문이다. 그러나 이 모드 구분이 오히려 vim의 장점으로 작용하기도 한다.


NORMAL Mode and EX Mode

NORMAL mode, as mentioned, is a state for navigation — moving the cursor, scrolling the screen, deleting content, pasting, and so on. Pressing : in NORMAL mode switches to EX mode, where you can enter commands.

EX mode originates from the concept of a line editor, derived from the era before visual interfaces when text was processed one line at a time.

To return to NORMAL mode from INSERT mode, press ESC. Pressing ESC twice guarantees a return to NORMAL mode regardless of the current state.


Entering INSERT Mode

INSERT mode is the state where text can be directly entered. From NORMAL mode, pressing any of i, I, a, A, o, O activates INSERT mode, shown by -- INSERT -- at the bottom of the screen. All of them enter INSERT mode, but each key differs in where the cursor is positioned when input begins.

  • i — starts input at the current cursor position

  • I — starts input at the beginning of the current line

  • a — starts input one position after the current cursor

  • A — starts input at the end of the current line

  • o — creates a new line below the current line and starts input there

  • O — creates a new line above the current line and starts input there

The cursor shape may appear as an underline, a block, or other forms. It is good practice to press ESC twice to ensure you are in NORMAL mode before trying each key to observe the differences in cursor placement.

vim INSERT 모드 진입 방법

INSERT 모드는 텍스트를 직접 입력할 수 있는 상태로, NORMAL 모드에서 i, I, a, A, o, O 중 하나를 누르면 화면 하단에 -- INSERT --가 표시되며 진입할 수 있다. 모두 INSERT 모드로 전환된다는 공통점이 있지만, 각 키마다 커서가 시작되는 위치가 다르다.

각 키의 동작 차이는 다음과 같다. i는 현재 커서 위치에서, I는 현재 줄의 맨 앞에서 입력이 시작된다. a는 현재 커서의 다음 글자 위치에서 입력이 시작되며, A는 현재 줄의 맨 끝에서 시작된다. o는 현재 줄의 다음 줄에 새 줄을 만들어 입력할 수 있고, O는 현재 줄의 이전 줄에 새 줄을 만들어 입력할 수 있다.

커서 모양도 밑줄, 네모 등 여러 형태로 표시될 수 있다. ESC를 습관적으로 두 번 눌러 NORMAL 모드로 확실히 전환한 뒤 각 키를 눌러보면 커서 위치가 달라지는 것을 직접 확인할 수 있다.


Creating an Example File and UTF-8 Encoding

Entering man ls > vimLS.txt saves the manual for the ls command into a file called vimLS.txt. man ls outputs the manual, and > redirects that output to a file. Running file vimLS.txt afterward shows the file's attributes — the result will show UTF-8 text.

This differs from earlier when file ~/.profile returned ASCII. ASCII is composed of 7 bits and can only represent 128 characters, which is not enough to include Korean and many other languages. UTF-8 was developed to overcome this limitation. It is a newly established encoding standard that accommodates languages with large character sets, such as Korean, Japanese, and Chinese, and is now used almost universally. When Korean characters fail to display properly, it is often referred to as a CJK problem - an abbreviation for Chinese, Japanese, Korean - indicating the system cannot represent those characters. The saved file can be opened in vim by running vim vimLS.txt.

vim 예시 파일 생성과 UTF-8 인코딩

man ls > vimLS.txt를 입력하면 ls 명령어의 설명서 내용이 vimLS.txt 파일로 저장된다. man lsls 명령어의 매뉴얼을 출력하는 명령어이고, >로 리다이렉트하여 그 내용을 파일에 저장하는 것이다. 이후 file vimLS.txt를 입력하면 해당 파일의 속성을 확인할 수 있는데, 결과로 UTF-8 text가 출력된다.

앞서 file ~/.profile에서는 ASCII로 출력되었던 것과 차이가 있다. ASCII는 7비트로 구성되어 128가지 문자만 표현할 수 있기 때문에 한글을 비롯한 다양한 언어를 표현하지 못한다. 이러한 한계를 극복하기 위해 등장한 것이 UTF-8 인코딩 방식이다. UTF-8은 한글, 일본어, 중국어처럼 표현해야 할 문자 수가 많은 언어를 수용하기 위해 새롭게 제정된 인코딩 방식으로, 요즘은 거의 대부분 UTF-8을 사용한다. 한글이 제대로 표시되지 않을 때 CJK 문제라는 표현을 쓰는데, 이는 Chinese, Japanese, Korean의 약자로 해당 언어들의 문자를 표현하지 못하는 상태를 의미한다. 이렇게 저장된 파일은 vim vimLS.txt를 입력하면 저장된 내용을 vim 편집기에서 확인할 수 있다.


vim Cursor Movement

Opening vim vimLS.txt displays information at the bottom such as "vimLS.txt" 249L, 8383B. Here, 249L is the total number of lines including blank lines, and 8383B is the number of bytes the document occupies. The 1,1 in the bottom right indicates the current cursor position — line (row) and column.

One thing to note about bytes: CJK characters — Korean, Japanese, Chinese — typically occupy 2 bytes. For example, the word "한글" appears as two characters visually, but internally it is stored as more bytes than that.

Cursor movement can be done with h, j, k, l instead of the arrow keys — left, down, up, and right respectively. This is a legacy from early keyboards that lacked arrow keys. Since computers at that time were paper-based, directional movement was unnecessary. In the modern era, arrow keys are available, but the h, j, k, l convention remains a vim tradition and is still fully supported.vim 커서 이동

vim vimLS.txt를 입력하면 편집기 화면이 열리며, 화면 하단에 "vimLS.txt" 249L, 8383B와 같은 정보가 표시된다. 여기서 249L은 빈 줄을 포함한 전체 줄 수를 의미하고, 8383B는 문서가 차지하는 바이트 수를 의미한다. 화면 오른쪽 하단의 1,1은 현재 커서의 위치로, 줄(row)과 칸(column)을 나타낸다.

바이트 수와 관련하여 한 가지 알아둘 점이 있다. CJK 문자, 즉 한국어, 일본어, 중국어는 보통 2바이트를 차지한다. 예를 들어 "한글"은 눈에 보이기엔 두 글자지만 컴퓨터 내부에서는 그보다 더 많은 바이트로 처리된다.

커서 이동은 방향키 대신 h, j, k, l 키로 할 수 있다. 각각 왼쪽, 아래, 위, 오른쪽에 해당한다. 이는 초기 키보드에 방향키가 없었던 시절의 흔적이다. 당시 컴퓨터는 종이 기반으로 작동했기 때문에 상하좌우 이동이 필요 없었고, 별도의 키 매핑이 필요했다. 현대에는 키보드가 발전하여 방향키를 사용할 수 있지만, h, j, k, l 방식은 vim의 전통으로 남아 있으며 vim improved에서도 동일하게 사용 가능하다.


Cursor Movement: Beginning and End of a Line

In NORMAL mode, 0, \(, and ^ allow quick movement within a line. 0 moves to the very beginning of the line, \) moves to the very end, and ^ moves to the first non-blank character of the line. For example, if there are spaces at the start of a line, 0 moves to the absolute beginning including those spaces, while ^ moves to where the actual content starts. This can also help identify whether the leading space was created with the spacebar or the tab key.

Note that cursor movement commands including h, j, k, l only work in NORMAL mode. Always confirm you have pressed ESC to switch to NORMAL mode before using them.

vim 커서 이동: 줄의 시작과 끝

NORMAL 모드에서 0, \(, ^ 키를 사용하면 커서를 줄 단위로 빠르게 이동할 수 있다. 0을 누르면 줄의 맨 앞으로, \)를 누르면 줄의 맨 끝으로 이동한다. ^를 누르면 줄에서 내용이 시작되는 첫 번째 문자로 이동한다. 예를 들어 줄 앞에 빈칸이 있는 경우, 0은 빈칸을 포함한 맨 앞으로 이동하지만 ^는 실제 내용이 시작되는 위치로 이동한다. 이를 통해 해당 빈칸이 스페이스바로 만들어진 것인지 탭 키로 만들어진 것인지도 확인할 수 있다.

주의할 점은 h, j, k, l을 비롯한 커서 이동 명령은 반드시 NORMAL 모드에서만 작동한다는 것이다. ESC 키를 눌러 NORMAL 모드로 전환된 것을 확인한 뒤 사용하도록 하자.


Screen-Level Movement

Beyond line-by-line movement, you can jump by entire screens. In NORMAL mode, Ctrl+f moves one full screen down, Ctrl+b moves one full screen up, Ctrl+d moves half a screen down, and Ctrl+u moves half a screen up. This is useful for navigating long files much faster than moving one line at a time.

vim 화면 단위 이동

한 줄씩 이동하는 것 외에도 화면 단위로 한 번에 이동할 수 있다. NORMAL 모드에서 Ctrl키와 함께 사용하며, Ctrl+f는 한 화면 아래로, Ctrl+b는 한 화면 위로 이동한다. Ctrl+d는 화면의 절반만큼 아래로, Ctrl+u는 화면의 절반만큼 위로 이동한다. 한 줄씩 이동하는 것보다 빠르게 원하는 위치로 점프할 수 있어 긴 파일을 탐색할 때 유용하다.


Jumping to a Specific Line

For files with tens of thousands of lines, even screen-level movement can take a long time. In NORMAL mode, pressing gg jumps to the first line, and pressing G jumps to the last line. Typing a line number followed by G jumps directly to that line.

This is one of the most powerful reasons to use vim — no need to scroll with a mouse to reach a specific location. While the experience varies by user, many people use vim not just because it looks impressive, but because it genuinely meets their needs.

vim 특정 줄로 이동

페이지가 수만 줄에 달하는 파일이라면 화면 단위 이동으로도 한참을 이동해야 한다. 이때 특정 줄로 바로 이동하는 기능을 활용할 수 있다. NORMAL 모드에서 gg를 누르면 첫 번째 줄로, 대문자 G를 누르면 맨 마지막 줄로 이동한다. 이동하고 싶은 줄 번호를 입력한 뒤 G를 누르면 해당 줄로 바로 이동할 수 있다.

이것이 vim을 사용하는 가장 강력한 이유 중 하나다. 마우스로 스크롤하지 않아도 원하는 위치로 즉시 이동할 수 있기 때문이다. 사용자에 따라 경험은 다르겠지만, vim을 사용하는 사람들은 단순히 멋있어서가 아니라 실제로 필요하기 때문에 사용하는 경우가 많다.


Word-Level Movement

Movement is also possible at the word level. In NORMAL mode, pressing w moves to the next word and b moves to the previous word.

One important thing to keep in mind is that case matters. For example, |, l, and I look visually similar but are entirely different characters. Catching these differences quickly comes from a developer's eye, and the more you work with computers from a developer's perspective, the more naturally this awareness develops.

vim 단어 단위 이동

한 문자씩 혹은 화면 단위 이동 외에도 단어 단위로 이동하는 것도 가능하다. NORMAL 모드에서 w를 누르면 다음 단어로, b를 누르면 이전 단어로 이동한다.

여기서 주의해야 할 점은 대소문자를 반드시 구분해야 한다는 것이다. 예를 들어 |, l, I는 시각적으로 비슷해 보이지만 모두 다른 문자다. 이러한 차이를 빠르게 캐치하는 것은 개발자적 감각에서 비롯되며, 컴퓨터를 개발자 입장에서 많이 다뤄볼수록 자연스럽게 익숙해진다.


Word-Level Movement 2: B and W

Unlike lowercase b and w, uppercase B and W use whitespace as the word boundary. Lowercase versions recognize special characters and punctuation as word boundaries, while uppercase versions only recognize spaces. Therefore, W moves to the word after the next space, and B moves to the word before the previous space. Since the movement range is broader than the lowercase versions, navigation is faster.

vim 단어 단위 이동 2: 대문자 B, W

앞서 살펴본 소문자 b, w와 달리 대문자 B, W는 빈칸을 기준으로 단어 단위 이동을 한다. 소문자는 특수문자나 구두점 등을 단어의 경계로 인식하지만, 대문자는 오직 빈칸만을 기준으로 삼는다. 따라서 W는 다음 빈칸 너머의 단어로, B는 이전 빈칸 너머의 단어로 이동한다. 이동 범위가 소문자보다 넓기 때문에 더 빠르게 이동할 수 있다.


Entering INSERT Mode 1: i and a

To type actual text or code in NORMAL mode, you need to switch to INSERT mode. The two most common keys are lowercase i and a. Both enter INSERT mode, but they differ in where input begins.

For example, if the cursor is on the second character of a 5-character text, pressing i starts input at the current position (second character), while pressing a starts input one position after (third character). In short, i starts at the current position and a starts one character to the right.

vim INSERT 모드 진입 1: ia

NORMAL 모드에서 실제 문자나 코드를 입력하려면 INSERT 모드로 전환해야 한다. 대표적인 방법이 소문자 ia이며, 둘 다 INSERT 모드로 진입하지만 커서 위치에 차이가 있다.

예를 들어 5칸짜리 텍스트에서 커서가 두 번째 칸에 위치해 있다고 가정하면, i를 누르면 현재 커서 위치인 두 번째 칸부터 입력이 시작된다. 반면 a를 누르면 현재 커서의 바로 다음 위치인 세 번째 칸부터 입력이 시작된다. 즉 i는 현재 위치에서, a는 현재 위치의 한 칸 뒤에서 입력이 시작된다는 차이가 있다.


Entering INSERT Mode 2: o and O

Lowercase o creates a new line below the current cursor position and begins input at the first character of that new line. Uppercase O creates a new line above the current cursor position and begins input at the first character of that new line.


Deleting and Undoing

In NORMAL mode, pressing x deletes the single character at the current cursor position. Pressing uppercase D deletes everything from the current cursor position to the end of the line. Pressing dd deletes the entire line.

For undoing, this is similar to Ctrl+Z in Windows. Pressing u in NORMAL mode undoes one action at a time, stepping back through previous states with each press. Uppercase U restores the entire current line to its state before any changes were made.

vim 삭제와 되돌리기

NORMAL 모드에서 x를 누르면 현재 커서 위치의 한 글자가 삭제된다. 대문자 D를 누르면 현재 커서 위치부터 줄의 끝까지 한 번에 삭제된다. dd를 누르면 커서가 있는 줄 전체가 삭제된다.

되돌리기는 윈도우의 Ctrl+Z와 유사한 개념이다. NORMAL 모드에서 u를 누르면 누를 때마다 이전 상태로 한 단계씩 되돌아간다. 대문자 U는 커서가 있는 줄 전체를 변경 이전 상태로 되돌린다.


Replacing a Single Character

As learned, x deletes a single character at the cursor position. To replace rather than delete a character, there are two methods.

Pressing ~ toggles the case of the character at the cursor position between uppercase and lowercase. This is useful in alphabetic language environments and does not apply to CJK characters like Korean, Japanese, or Chinese.

In NORMAL mode, pressing r followed by a desired key replaces the character at the cursor with the newly pressed character — a quick way to swap a single character without the extra step of deleting and retyping.

vim 한 글자 바꾸기

앞서 x는 현재 커서 위치의 한 글자를 삭제한다고 배웠다. 삭제가 아닌 한 글자만 바꾸고 싶을 때는 두 가지 방법을 사용할 수 있다.

~를 누르면 커서 위치의 문자 대소문자가 전환된다. 알파벳 기반의 언어권에서 유용하게 활용할 수 있으며, 한국어, 일본어, 중국어와 같은 CJK 문자에는 해당되지 않는다.

NORMAL 모드에서 r을 누른 뒤 원하는 키를 입력하면 현재 커서 위치의 글자가 새로 입력한 문자로 바뀐다. 삭제 후 다시 입력하는 번거로움 없이 한 글자를 빠르게 교체할 수 있다.


Searching for Content

In NORMAL mode, pressing / moves the cursor to the bottom of the screen. Type the search term and press Enter to jump to the matching location. / searches in the forward (downward) direction from the current cursor position. Pressing n continues searching in the same direction, while N searches in the opposite direction.

Pressing ? instead searches in the backward (upward) direction. In this case, n continues in the same direction (upward) and N goes in the opposite direction (downward). Note that forward and backward here refer to the direction of the search, not the visual position on screen.

vim 내용 찾기

NORMAL 모드에서 /를 누르면 화면 맨 아래로 커서가 이동한다. 찾고자 하는 문구를 입력하고 엔터를 누르면 해당 내용이 있는 위치로 이동한다. /는 현재 커서 위치에서 뒤쪽 방향으로 탐색을 시작한다. 이때 n을 누르면 같은 방향(뒤쪽)으로 계속 탐색하고, N을 누르면 반대 방향(앞쪽)으로 탐색한다.

반대로 ?를 누르고 문구를 입력하면 앞쪽 방향으로 탐색을 시작한다. 이 경우 n은 진행 방향 그대로 앞쪽으로, N은 반대 방향인 뒤쪽으로 탐색한다. 여기서 앞쪽과 뒤쪽은 화면 기준이 아닌 탐색이 진행되는 방향을 기준으로 한다는 점에 주의해야 한다.


Other vim Commands

Commands used after input can be referenced from the ed editor documentation. There are a great many commands, and knowing regular expressions will be an advantage in understanding and using them.

A notable example is :s/short/SHORT/gc, which replaces all instances of short with SHORT in the file. This is similar to the sed 's/-/*/' covered earlier. Here, gc stands for global confirm — it finds and replaces throughout the entire document while asking for confirmation each time.

Regular expressions are a vast topic — broad enough to be a subject on their own — so it is not possible to cover everything in this session. It is recommended to explore them separately when time allows, or through a related course.

For learning vim, the built-in help tutorial is a good resource, and https://vim-adventures.com/ offers a game-based approach to learning vim commands. Note that the site is paid.

vim 기타 명령어

입력 후 사용하는 명령어는 ed 편집기 사용법을 참고하면 된다. 사용법이 매우 많으며, regular expression(정규 표현식)을 알고 있다면 이해와 활용에 유리하다.

대표적인 예로 :s/short/SHORT/gc는 파일 안의 모든 shortSHORT로 변경하는 명령어다. 앞서 배운 sed 's/-/*/'와 유사한 방식이다. 여기서 gc는 global confirm의 약자로, 문서 전체에서 찾아 바꾸되 매번 확인을 거친다는 의미다.

정규 표현식은 그 자체로 하나의 과목이 될 만큼 방대한 주제이므로 이번 시간에 모두 다루기는 어렵다. 관련 과목을 수강하거나 시간이 날 때 별도로 찾아보는 것을 권장한다.

vim 학습에 도움이 되는 자료로는 vim 내장 help의 튜토리얼이 있으며, https://vim-adventures.com/ 에서 게임 형식으로 사용법을 익힐 수도 있다. 단, 해당 사이트는 유료임을 참고하자.