Текстовый редактор командная строка windows

Problem Formulation

Given is a text file, say my_file.txt. How to modify its content in your Windows command line working directory?

I’ll start with the most direct method to solve this problem in 90% of cases and give a more “pure” in-terminal method afterward.

Method 1: Using Notepad

The easiest way to edit a text file in the command line (CMD) on your Windows machine is to run the command notepad.exe my_text_file.txt, or simply notepad my_text_file.txt, in your cmd to open the text file with the visual editor Notepad.

notepad.exe my_file.txt

You can also skip the .exe prefix in most cases:

notepad my_text_file.txt

Now, you may ask:

💡 Is Notepad preinstalled in any Windows installation? The answer is: yes! Notepad is a generic text editor to create, open, and read plaintext files and it’s included with all Windows versions.

Here’s how that looks on my Win 10 machine:

When I type in the command notepad.exe my_text_file.txt, CMD starts the Notepad visual editor in a new window.

I can then edit the file and hit CTRL + S to save the new contents.

But what if you cannot open a text editor—e.g. if you’re logged into a remote server via SSH?

Method 2: Pure CMD Approach

If you cannot open Notepad or other visual editors for some reason, a simple way to overwrite a text file with built-in Windows command line tools is the following:

  • Run the command echo 'your new content' > my_file.txt to print the new content using echo and pipe the output into the text file my_text_file.txt using >.
  • Check the new content using the command type my_text_file.txt.
C:\Users\xcent\Desktop>echo 'hello world' > my_file.txt
C:\Users\xcent\Desktop>type my_file.txt
'hello world'

Here’s what this looks like on my Windows machine, where I changed my_file.txt to contain the text 'hello world!':

This is a simple and straightforward approach to small changes. However, if you have a large file and you just want to edit some minor details, this is not the best way.

Method 3: Change File Purely In CMD (Copy Con)

If you need a full-fledged solution to edit potentially large files in your Windows CMD, use this method! 👇

To create a new file in Windows command prompt, enter copy con followed by the target file name (copy con my_file.txt). Then enter the text you want to put in the file. To end and save the file, press Ctrl+Z then Enter or F6 then Enter.

copy con my_file.txt

How this looks on my Win machine:

A couple of notes:

💡 Info: To edit an existing file, display the text by using the type command followed by the file name. Then copy and paste the text into the copy con command to make changes. Be careful not to make any typos, or you’ll have to start over again. Backspace works if you catch the mistake before pressing Enter. Note that this method may not work in PowerShell or other command line interfaces that don’t support this feature.

Method 4: If you SSH’d to a Unix Machine

Of course, if you have logged in a Unix-based machine, you don’t need to install any editor because it comes with powerful integrated editors such as vim or emacs.

One of the following three commands should open your file in a terminal-based editing mode:

vim my_text_file.txt
vi my_text_file.txt
emacs my_text_file.txt

You can learn more about Vim here.

Summary

To edit a file.txt in the command line, use the command notepad file.txt to open a graphical editor on Windows.

If you need a simple file edit in your terminal without a graphical editor and without installation, you can use the command echo 'new content' > file.txt that overwrites the old content in file.txt with new content.

If you need a more direct in-CMD text editor run copy con file.txt to open the file in editing mode.

If you’re SSH’d into a Unix machine, running the Vim console-based editor may be the best idea. Use vim file.txt or vi file.txt to open it.

Feel free to join our email coding academy (it’s free):

👉 Recommended: How to Edit a Text File in PowerShell (Windows)

Home » KB » SysAdmin » 5 Best Command-Line Text Editors for Linux, Windows and Mac

Editing files quickly and effectively using the command line is vital for every user or system administrator. Whether it is a configuration file, user file, text document, or log, it is a good idea to have a reliable and powerful command-line text editor.

This article describes the top five open-source command-line text editors available on Windows, Linux, and macOS.

Five best command-line text-editors for Windows Linux and macOS.

Top 5 Command-Line Text Editors for Linux, Windows & Mac

Choosing the right command-line text editor depends on your needs and comfort level. The top five command line editors we have chosen to cover in this article are:

  • Vim
  • Emacs
  • Nano
  • Micro
  • Gedit

The table below shows an overview of the editors’ key features:

Editor Supported OS Capabilities Expandability GUI
Vim Windows, Linux, macOS Highly configurable, syntax highlighting, code folding, powerful text commands. Extensive plugins available. Optional GUI through gVim.
Emacs Windows, Linux, macOS Supports multiple languages, email, calendar, and more. Highly extensible with packages and modes. Built-in GUI version available.
Nano Windows, Linux, macOS Simple and user-friendly, basic text editing. Limited, but supports syntax highlighting and basic plugins. /
Micro Windows, Linux, macOS Modern and intuitive, mouse support, multiple cursors, syntax highlighting. Supports plugins written in Lua. /
Gedit Windows, Linux, macOS Full-featured text editor, syntax highlighting, search/replace. Supports plugins to extend functionality. Primarily GUI, terminal mode on Linux.

For more information about each text editor, refer to the sections below.

1. Vim

Vim command-line text editor logo.

Vim is a very flexible text editor that is suitable for performing many different operations on text. It is widely regarded as one of the most powerful text editors available. Vim was released in 1991 as an enhanced version of the Vi editor, and it has since become a highly configurable text editing tool.

The editor is supported on Windows, Linux, and macOS. It has a steep learning curve, but once you learn how to use it, it becomes incredibly efficient. Some of its features include syntax highlighting, code folding, find and replace with regular expressions, complex text transformations with minimal keystrokes, color schemes, and much more.

Vim’s functionality can be even further extended with a wide variety of plugins available through its plugin manager. The plugins enable syntax highlighting, auto-completion, integration with version control systems, and more.

The editor also comes with a graphical user interface, gVim, which adds menus and toolbars while retaining Vim’s powerful command-line interface. The following image shows Vim’s terminal and GUI view:

Comparing the Vim text editor CLI and GUI.

Vim’s flexibility and power make it the top choice for advanced users who need a highly customizable text editor.

2. Emacs

GNU Emacs command-line text editor logo.

GNU Emacs is a powerful text editor that is part of an entire app ecosystem. It was created by Richard Stallman in 1976 and has since become one of the most extensible and feature-rich editors available. Emacs is supported on Windows, Linux, and macOS.

The editor is highly versatile and supports editing in almost every programming language. Its built-in package manager provides functionalities that range from email clients to calendar systems. Its powerful scripting language, Emacs Lisp, enables users to customize and automate almost any aspect of the text editor.

Emacs’ functionality can be extended with various packages and modes, including specialized programming environments, document processing, and even games. The editor is also available in the GUI mode, with a more user-friendly interface with a menu and toolbars. The image below shows its terminal and GUI view:

Emacs text editor CLI and GUI comparison.

Emacs focuses on adaptability, making it a preferred tool for users who want an all-in-one editor capable of much more than text manipulation.

3. Nano

GNU Nano command-line text editor logo.

GNU Nano is the go-to text editor for many users who need something simple and straightforward. It was designed with ease of use in mind, as part of the GNU Project that provides a more user-friendly alternative to the traditional Unix text editor, Pico.

Nano is supported on Windows, Linux, and macOS, and it offers basic text editing functions like cut, copy, paste, and simple search/replace, all within a clean and minimal interface. Unlike Vim or Emacs, Nano does not require users to remember complex commands. Most functions are accessible via keyboard shortcuts that the terminal displays at the bottom of the screen:

Example of the Nano text editor.

Although Nano is less flexible than Vim or Emacs, it supports some basic enhancements such as syntax highlighting and automatic indentation through configuration files. However, there is no GUI version, as Nano is a command-line-only editor.

Nano’s simplicity and accessibility make it a great choice for beginners or anyone who needs to make quick edits without the overhead of more complex editors.

4. Micro

Micro is a modern text editor that combines many benefits of traditional editors like Vim and Emacs with simplicity and ease of use. It is intuitive, making it accessible even to those new to command-line editors.

The editor is available on Windows, Linux, and macOS, and it offers a user-friendly experience on all operating systems. It boasts features like mouse support, multiple cursors, and syntax highlighting out of the box. Its default keybindings are easy to learn.

Unlike many other command-line editors, Micro provides a more modern interface with smooth scrolling, split-pane editing, and an easy-to-navigate help system. The features are expandable through plugins, such as auto-completion, theming, and more.

Although Micro is a strictly command-line editor, its modern interface provides an experience similar to that of a GUI editor. The image below shows an example of its CLI:

It is an excellent choice for users who want the power of a command-line editor with a more modern and user-friendly interface.

5. Gedit

Gedit command-line text editor logo.

Gedit is primarily the default text editor for the GNOME desktop environment. Although it is mainly a graphical editor, it can be used in terminal mode on Linux, making it a versatile option for those who switch between GUI and CLI.

The editor is available in Windows and Linux, with unofficial macOS support. Some of the text editors’ features include syntax highlighting, search and replace, file backups, text wrapping, and more.

Gedit’s functionality can be extended with plugins for additional features like version control integration, spell checking, and more advanced editing tools. Although Gedit is primarily a graphical editor, it can also be launched in terminal mode on Linux systems. It is one of the few editors that is GUI-first.

Example of the Gedit GUI.

The editor’s ease of use and cross-platform availability make it suitable for those who want a consistent experience across different environments.

Conclusion

This article listed the top command-line editors for Linux, Windows, and macOS. Choosing between them depends on what you expect from a text editor. Each editor has its strengths, so whether you are looking for raw power, simplicity, or something in between, this list should help you find the right tool for the job.

If you are a Linux user, check out our list of 7 best Linux text editors.

Was this article helpful?

YesNo

Редактирование файлов

Основы командной строки

  • Nano
  • Vim

Для редактирования файлов в командной строке используют редакторы Nano, Vim и Emacs. В этом уроке мы обсудим два редактора из этого списка.

В большинстве случаев в системе установлен только Vim, поэтому важно владеть базовыми навыками обращения с ним. Эти редакторы запускаются прямо в терминале, хотя Vim и Emacs имеют режим, в котором они запускаются как отдельные приложения.

Nano

Nano — очень простенький текстовый редактор, похожий на Блокнот в Windows, хотя по возможностям он богаче и даже способен подсвечивать содержимое файлов:

nano .profile

Nano

После запуска редактора внизу открывается панель с подсказками, какие горячие клавиши доступны для использования. Символ ^ означает клавишу Ctrl.

Например, нажав Ctrl + x, вы можете выйти из редактора. При выходе нужно уточнить, хотите ли вы сохранить изменения:

  • Сохранить — y (yes)
  • Не сохранять — n (no)

В принципе, больше ничего интересного про Nano сказать нельзя. Это обычный редактор, который подходит для несложных изменений в файлах, но им совсем неудобно пользоваться для работы над проектами с множеством файлов и сложным кодом.

Vim

Совсем другое дело — это Vim (сокращение от Vi Improved). Это свободный текстовый редактор, созданный на основе более старого vi (visual editor).

Это редактор, который имеет уникальную модель работы:

vim .profile

Vim

Ключевое отличие Vim от остальных редакторов — наличие режимов. В обычных редакторах мы открываем файл и сразу можем приступать к редактированию. В отличие от них, Vim запускается в режиме COMMAND — это режим команд, при котором нажатие на любую клавишу воспринимается как сигнал к какому-то действию.

Если вы не знаете команд, то лучше ничего не трогать, иначе на экране начнется хаос. Обычное редактирование текста выполняется в режиме ввода — INSERT. Попасть в него можно с помощью клавиши i. Для выхода в режим команд достаточно нажать Esc или комбинацию Ctrl + [.

Всего у Vim есть четыре основных режима работы:

  • Командный режим — это режим по умолчанию. В нем можно перемещаться по файлу, вносить изменения с помощью комбинаций клавиш, удалять и искать текст
  • Режим вставки — это режим ввода текста с клавиатуры. Здесь все работает так, как вы привыкли это делать в обычных редакторах
  • Визуальный режим — выделение произвольных участков текста
  • Режим командной строки — собственная командная строка для редактора текста, из которой можно выполнять множество разнообразных команд

Vim по праву считается редактором с самым высоким порогом входа, и разработчики даже шутят на эту тему:

Editors Learning Curve

Конечно, в этой шутке есть доля правды. Но чем дольше вы будете осваивать программирование, тем чаще вы будете встречать опытных и известных разработчиков, которые полностью работают на Vim. Не последнюю роль в этом играют расширения.

Посмотрев на Vim без плагинов, сложно поверить, что благодаря расширениям он может стать очень навороченным:

Vim

Подробнее о том, почему так происходит и что особенного в Vim, написано в нашем руководстве. Крайне рекомендуем к прочтению.

Говорят, что самое сложное в Vim — это выйти, поэтому подготовимся заранее. Обсудим, как выйти из Vim:

  • Убедитесь, что вы находитесь в командном режиме. На всякий случай нажмите Esc или комбинацию Ctrl + [
  • Затем наберите : (символ «двоеточие») — эта команда переведет вас в режим командной строки
  • В конце введите q! и нажмите Enter

Так вы выйдете из Vim без сохранения изменений. Если набрать :wq, то перед выходом сохранятся все изменения. Если вы хотите просто сохраниться без выхода, то наберите :w.

Кстати, большая часть Хекслета сделана именно в Vim, включая код самой платформы, некоторые текстовые курсы и эту строчку.


Дополнительные материалы

  1. Vim
  2. Sed (Stream Editor)

Открыть доступ

Курсы программирования для новичков и опытных разработчиков. Начните обучение бесплатно


  • 130 курсов, 2000+ часов теории

  • 1000 практических заданий в браузере

  • 360 000 студентов

Наши выпускники работают в компаниях:

Open Notepad With the Command Prompt

Usually, running a program from the command prompt requires you to navigate to the application’s directory first. Windows system programs including Notepad, however, work from any directory. Open the command prompt — press Windows-R and run Cmd, or in Windows 8, press Windows-X and select Command Prompt — and type Notepad to run the program. On its own, this command opens Notepad in the same way as if you had loaded it through the Start menu or Start screen.

Loading Notepad from command prompt

An administrative command prompt also works, but isn’t required.

Image Credit:
Image courtesy of Microsoft

To load a text file from the prompt, enter its name — including directory and extension — in quotes, such as Notepad «C:\Documents\File.txt». You have to include the full directory of the file unless the file is in the prompt’s current directory. If it is, simply use the file’s name and extension in quotes: Notepad «File.txt». Optionally, you can omit the quotes if your file name has no spaces.

Command Line Arguments

In addition to loading a file, Notepad has a few command line arguments for changing the program’s encoding system and printing.

Encoding Options

By default, Notepad automatically detects the type of encoding used in a text file when loading it. To override the automatic detection, enter either /a for ANSI or /w for Unicode (UTF-16) prior to the file’s name. For example, Notepad /a «C:\Documents\File.txt» opens File.txt with ANSI encoding, regardless of the encoding used when saving the file.

Printing Options

Print a text file directly from the command prompt using the default printer by inserting /p prior to the file’s name: Notepad /p «C:\Documents\File.txt».

Printing from command prompt

Notepad automatically closes after printing.

Image Credit:
Image courtesy of Microsoft

To use an alternative printer, change /p to /pt and enter the printer’s full name in quotes after the file name. For example, Notepad /pt «C:\Documents\File.txt» «InkJet Printer 1500» prints File.txt to a printer named Inkjet Printer 1500. For a network printer, give its location on the network, such as «\HOSTPC\PrinterName».

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Office 2019 download windows org
  • C windows system32 dxcpl exe
  • Как сделать устранение неполадок на windows 10
  • Что делать если забыл пароль от компа на windows 10
  • Windows 10 переименовать пользователя администратор