From Wikipedia, the free encyclopedia
For the Unix command that looks up command names, see type (Unix).
type
The BW-DOS |
|
Developer(s) | Various open-source and commercial developers |
---|---|
Operating system | RT-11, OS/8, RSX-11, TOPS-10, TOPS-20, VMS, CP/M, MP/M, CDOS, TRIPOS, HDOS, AmigaDOS, DOS, MSX-DOS, FlexOS, PC-MOS, SpartaDOS X, 4690 OS, OS/2, Windows, AROS, ReactOS, SymbOS |
Platform | Cross-platform |
Type | Command |
License | PC-MOS: GPLv3 AROS: AROS Public ReactOS: GPLv2 |
In computing, type is a command in various command-line interpreters (shells) such as COMMAND.COM
, cmd.exe
, 4DOS/4NT and Windows PowerShell used to display the contents of specified files on the computer terminal. The analogous Unix command is cat.
The command is available in the operating systems DEC RT-11,[1] OS/8,[2] RSX-11,[3] TOPS-10,[4] TOPS-20,[5] VMS, Digital Research CP/M,[6] MP/M,[7][8] MetaComCo TRIPOS,[9] Heath Company HDOS,[10] AmigaDOS,[11] DOS, FlexOS,[12] TSL PC-MOS,[13] SpartaDOS X,[14] IBM/Toshiba 4690 OS,[15] IBM OS/2, Microsoft Windows,[16] ReactOS,[17] AROS,[18] and SymbOS.[19]
The type
command is supported by Tim Paterson’s SCP 86-DOS.[20] On MS-DOS, the command is available in versions 1 and later.[21] DR DOS 6.0 also includes an implementation of the TYPE
command.[22]
It is also available in the open source MS-DOS emulator DOSBox and the EFI shell.[23]
In Windows PowerShell, type is a predefined command alias for the Get-Content Cmdlet which basically serves the same purpose. TYPE originated as an internal command in 86-DOS.
The command-syntax and feature set between operating systems and command shell implementations can differ as can be seen in the following examples.
In Digital Equipment Corporation’s RT-11, the command accepts up to six input file specifications. Multiple file specifications are separated with commas.
The default filetype is .LST. Wildcards are accepted in place of filenames or filetypes.
The command-syntax on RT-11 is:
TYPE[/options] filespecs
COPIES:n
– Specify the number of times the file will be typedDELETE
– Delete the file after typing itLOG
– Log the names of the files typedNEWFILES
– Only files dated with the current system date will be typedNOLOG
– Suppress the log of the files typedQUERY
– Require confirmation before typing each fileWAIT
– Wait for user response before proceeding with the type
TYPE/COPIES:3 REPORT
TYPE/NEWFILES *.LST
DR CP/M, MP/M, FlexOS
[edit]
In Digital Research CP/M, the command expands tabs and line-feed characters (CTRL-I), assuming tab positions are set at every eighth column.
The command does not support wildcard characters on FlexOS.[12]
The command-syntax on CP/M is:
TYPE ufn
Note: ufn = unambiguous file reference
In MP/M, the command has a pause mode. It is specified by entering a ‘P’ followed by two decimal digits after the filename. The specified number of lines will be displayed and then the command will pause until a carriage return is entered.[7]
The Software Link’s PC-MOS includes an implementation of TYPE
. Like the rest of the operating system, it is licensed under the GPL v3.[24]
It supports an option to display the file content in hexadecimal form.[13]
The command-syntax on PC-MOS is:
.TYPE filename [/h]
filename
– The name of the file to display/h
– Display content in hexadecimal form
Microsoft Windows, OS/2, ReactOS
[edit]
type
commandThe command supports wildcard characters. In Microsoft Windows and OS/2 it includes the filename in the output when typing multiple files.
The command-syntax on Microsoft Windows and ReactOS is:
type [Drive:][Path]FileName
[Drive:][Path]FileName
– This parameter specifies the location and name of the file or files to view. Multiple file names need to be separated with spaces./?
– This parameter displays help for the command.
- List of DOS commands
- List of Unix commands
- ^ «RT-11 HELP FILE». paleoferrosaurus.com. Archived from the original on 2018-07-17. Retrieved 2018-07-16.
- ^ «Concise Command Language» (CCL).«OS/8 Handbook» (PDF). April 1974. Retrieved 28 November 2017.
- ^ John F. Pieper (1987). RSX A Guide for Users (PDF). Digital Equipment Corporation. ISBN 0-932376-90-8. Retrieved 2020-09-19.
- ^ TOPS-10 Operating System Commands Manual (PDF). Digital Equipment Corporation. August 1980. Archived from the original (PDF) on 2020-08-09. Retrieved 2019-02-17.
- ^ «TOPS-20 Command manual» (PDF). Archived from the original (PDF) on 2020-08-09. Retrieved 2018-07-18.
- ^ «Manual» (PDF). www.cpm.z80.de. Retrieved 2020-09-19.
- ^ a b Digital Research (July 1981) [1979]. MP/M — Multi-Programming Monitor Control Program — User’s Guide (PDF) (4 ed.). Pacific Grove, CA, USA: Digital Research. Archived (PDF) from the original on 2017-01-04. Retrieved 2017-01-04.
- ^ Digital Research (1981-09-25). MP/M-86 Operating System — User’s Guide (PDF) (1 ed.). Pacific Grove, CA, USA: Digital Research. Archived (PDF) from the original on 2017-01-04. Retrieved 2017-01-04.
- ^ «Manual» (PDF). www.pagetable.com. Retrieved 2020-09-19.
- ^ Heath Company. «Software Reference Manual HDOS SYSTEM Chapter 2 General Operations» (PDF). Archived from the original (PDF) on 2017-08-07. Retrieved 2020-02-08.
- ^ Rügheimer, Hannes; Spanik, Christian (September 19, 1988). AmigaDOS quick reference. Grand Rapids, Mi : Abacus. ISBN 9781557550491 – via Internet Archive.
- ^ a b FlexOS User’s Guide Version 1.3 (PDF). 1.3 (1 ed.). Digital Research. November 1986. 1073-2003-001. Archived (PDF) from the original on 2019-03-30. Retrieved 2019-04-23.
- ^ a b «roelandjansen/pcmos386v501». GitHub. 2 January 2022.
- ^
SpartaDOS X 4.48 User Guide - ^ «Users guide» (PDF). archive.org. Retrieved 2020-09-19.
- ^ «Microsoft TechNet Type article». 11 September 2009.
- ^ «reactos/reactos». GitHub. 3 January 2022.
- ^ «AROS Research Operating System». aros.sourceforge.io.
- ^ «Data sheet». www.symbos.de. Retrieved 2020-09-19.
- ^ 86-DOS — Disk Operating System for the 8086 — User’s Manual (PDF). Version 0.3 (Preliminary ed.). Seattle, Washington, USA: Seattle Computer Products, Inc. 1980. Archived from the original (PDF) on 2019-07-14. Retrieved 2019-07-14. (59 pages)
- ^ Wolverton, Van (2003). Running MS-DOS Version 6.22 (20th Anniversary Edition), 6th Revised edition. Microsoft Press. ISBN 0-7356-1812-7.
- ^ DR DOS 6.0 User Guide Optimisation and Configuration Tips
- ^ «EFI Shells and Scripting». Intel. Retrieved 2013-09-25.
- ^ Jansen, Roeland (8 February 2018). «pcmos386v501: PC-MOS/386 v5.01 final release including cdrom driver sources» – via GitHub.
- Townsend, Carl (1983). Practical Guide to CP/M. Dilithium Press. ISBN 978-0880560771.
- Kathy Ivens; Brian Proffit (1993). OS/2 Inside & Out. Osborne McGraw-Hill. ISBN 9780078818714.
- John Paul Mueller (2007). Windows Administration at the Command Line for Windows Vista, Windows 2003, Windows XP, and Windows 2000. John Wiley & Sons. ISBN 978-0470165799.
- type | Microsoft Docs
TYPE is used mostly to view small ASCII files, like AUTOEXEC.BAT.
But it can also be used to:
- View text files that may be in use
- Remove a line from a text file
- Show size of files in use
- Convert Unicode to ASCII vv
- Convert «solitary» linefeeds to CR/LF pairs
View text files that may be in use
TYPE has at least one feature that makes it well suited to perform other tasks than plain text file viewing: it doesn’t lock the file it views.
This makes it an excellent program to view and even copy log files that are locked by another program.
The viewing will be obvious, here, but how about copying? Take a look at the example:
TYPE logfile.log > logfile.bak
Without the redirection to logfile.bak this would show the contents of logfile.log on screen.
Because of the redirection, though, these contents will now be stored in logfile.bak.
That way, the content of logfile.bak will be identical to logfile.log’s, though it will have a different timestamp.
This may be useful if you need to copy a text file that may be in use, when COPY
may fail.
Remove a line from a text file
This example demonstrates the combined use of TYPE and FIND to remove a line from an ASCII file (warning: real DOS only):
TYPE C:\CONFIG.SYS | FIND /V /I "SHARE.EXE" > C:\CONFIG.SYS
Since we use piping of TYPE’s standard output to FIND’s standard input, the content of CONFIG.SYS is stored in one or more temporary files before FIND’s standard output will overwrite CONFIG.SYS again.
Without piping to FIND’s standard input, CONFIG.SYS would be opened by TYPE and at the same time be overwritten by TYPE’s standard output.
This would result in either an error message (if you’re lucky) or an empty CONFIG.SYS.
Warning: | This trick won’t always work in multi-tasking environments like Windows NT or OS/2! You may find that you end up with an empty file using this trick. Use different source and target file names to be on the safe side. |
Show size of files in use
I often use TYPE to check a download’s progress:
If you use DIR to display file sizes, files being downloaded seem to have a file size of 0 bytes.
By using TYPE once to display the contents of the file, next time DIR will show the actual amount of bytes already downloaded.
This won’t hurt the download, since TYPE does in no way lock the file.
Use TYPE and DIR again to check on download progress:
DIR download_in_progress TYPE download_in_progress > NUL DIR download_in_progress
download_in_progress is the name of the file being downloaded.
Convert Unicode to ASCII vv
In Windows 2000 and later, TYPE offers a simple method to convert Unicode files to ASCII:
TYPE MyUnicode.txt > MyASCII.txt
Or, if «extended» ASCII characters like ë
or à
may be involved:
CHCP 1252 TYPE unicode.txt > ascii.txt
1252 is the most commonly used codepage for western languages in Windows 2000 and later.
Use a different code page for other languages.
Until recently, I believed conversion from ASCII to Unicode to be more complicated.
But then Jacques Bensimon showed me a really simple way:
CMD /U /C TYPE ascii.txt > unicode.txt
A note from Jacques Bensimon:
I thought I’d point out that, although the technique I mentioned does correctly convert ANSI characters to Unicode, the resulting file (which is exactly twice the size of the original) does not comply perfectly with what appears to be the standard for a Unicode text file (at least as far as Windows is concerned):
a file saved as Unicode by Windows (e.g. Notepad) has the 2-byte header0xFF 0xFE
as its first two characters and I’ve noticed that some programs that expect a Unicode file (for example a custom dictionary file in Office 2007) will not accept a «bare» Unicode file without that header.An easy way to take care of this (when necessary) is to first create and keep somewhere an empty Unicode text file (let’s call it UniHeader.txt) consisting only of the two bytes in question (just create an empty text file and save it as Unicode using Notepad to achieve this).
From then on, when you want to convert an ANSI text file to a «true» Unicode text file, you can use the following two commands:
COPY /Y UniHeader.txt Unicode_Output.txt
CMD /U /C Type ANSI_Input.txt >> Unicode_Output.txtJust a variation on the original theme, but this creates an output file the size of which is twice the original size + 2.
Personally, I prefer a «self-contained» batch file that doesn’t need a helper file, so I slightly modified Jacques’ idea:
> Unicode_Output.txt ECHO.▌■ CMD /U /C Type ANSI_Input.txt >> Unicode_Output.txt
Note the ▌■
at the end of the first command line: these represent the 2 characters Jacques mentioned.
They are not the actual characters, as these cannot be displayed on a web page: see Note 2!
Not every editor will allow the insertion of the 2 required characters, but any dedicated programming/scripting editor will.
Too bad this solution adds an extra carriage return/linefeed.
Jacques came with a solution once again:
If a non-native Windows utility is allowed, echo.exe (a port of the Unix version of echo) can echo arbitrary characters (specified as octal values) and can optionally not output any trailing newline characters (-n switch), so you can use:
echo.exe -n \377\376> Unicode_Output.txt
The «.exe» is necessary (unless you rename the utility) to avoid conflict with the internal
ECHO
command.
You can use the parameter «— help» to see the full echo.exe syntax.
Or, if you still have a copy of BATCHMAN available somewhere, you may want to try its CECHO C
command:
BATCHMAN CECHO C 07, ▌■> Unicode_Output.txt CMD /U /C Type ANSI_Input.txt >> Unicode_Output.txt
Or use the «almost native» CHOICE command (alternative solution, also by Jacques Bensimon):
CHOICE /N /M ▌■ < NUL 2> NUL > Unicode_Output.txt
Keep in mind, though, that CHOICE will insert an extra space.
Thanks Jacques
Update: | Carlos M. solved the Unicode header problem brilliantly:
Without View and download his A2U.bat for more details. Thanks Carlos |
|
Notes: | (1) | To save and restore the original codepage, use this command before changing the codepage:
or in case your Windows version appends a dot at the end of and then use the following command to restore the original codepage afterwards: |
(2) | Even though TYPE has been successfully used to convert to ASCII or Unicode on many computers, it has been reported to fail occasionally. This may be caused by copying the batch code from this web page, instead of downloading the ZIP files containing the code. There is NO WAY to correctly display the ASCII characters 0xFF and 0xFE, required for the Byte Order Mark, on a web page. |
|
(3) | In case you are one of those «lucky» few who still cannot get this working, download and use ASCII2Uc.vbs (or ASCII2Uc.bat) and Txt2ASCI.vbs instead:
|
Convert «solitary» linefeeds to CR/LF pairs
In Windows NT and later, TYPE combined with MORE offers a convenient way to convert solitary linefeeds (i.e. Unix text files) to carriage return/linefeed pairs:
TYPE input_filename | MORE /E /P > output_filename
- Detect file encoding (Unicode or ASCII)
page last modified: 2017-07-25; loaded in 0.0047 seconds
Позволяет вывести на экран то, что находится внутри текстового документа. Предполагается, что внести какие-либо изменения не получится.
Синтаксис
type [диск_компьютера:][путь] название_документа
Расшифровка значений
[диск_компьютера:][путь] название_документа
Позволяет установить, где именно располагается интересующий документ. Можно одновременно указать несколько файлов и для их разделения предусматривается применение пробелов.
/?
Предоставление справочных данных.
Особенности
- В некоторых ситуациях необходимо заключать текст внутрь кавычек. Это требуется применять при наличии диска с NTFS типом файловой системы и использовании пробелов в названии документа.
- Не исключено возникновение двоичных символов. Это происходит в случае просмотра двоичных файлов. Не рекомендуется применять type с целью просмотра документов данного вида.
Если вы оказались без доступа к чему-либо кроме командной строки или Windows PowerShell и по какой-то причине вам требуется возможность создания или чтения текстовых файлов, это вполне реализуемо, причем более чем одним методом.
В этой инструкции подробно о работе с текстовыми файлами в командной строки или PowerShell (разумеется, можно и в Терминале Windows) — создание и сохранение текстовых файлов, их вывод и чтение в консоли. Если вам требуется вывести результаты выполнения команды в файл, вы можете использовать отдельную инструкцию на эту тему.
Создание текстовых файлов в командной строке
Возможность создания текстовых файлов доступна как в командной строке (cmd.exe), так и в PowerShell. Начнем с первого варианта.
Во всех случаях учитывайте, что при использовании кириллицы потенциально возможны проблемы с кодировкой, а в некоторых случаях кодировка может отличаться при использовании разных команд.
Команда ECHO
Команда командной строки echo предназначена для вывода текстовых сообщений в окне консоли, например, при выполнении сценария в bat-файле, но может быть использована и для вывода текста в файл, благодаря возможности использования оператора «>» для перенаправления вывода из консоли в файл.
Пример команды:
echo Содержимое текстового файла > file.txt
В результате её выполнения в текущей рабочей папке командной строки будет создан файл с именем file.txt и содержимым «Содержимое текстового файла».
COPY CON
Команда copy с параметром con позволяет скопировать содержимое консоли в файл. Использование возможности будет состоять из следующих шагов:
- Введите команду
copy con имя_файла.txt
файл не будет создан, но после выполнения указанной команды у вас появится возможность набрать содержимое этого файла, которое по завершении процесса будет в него сохранено.
- Курсор переместится на строчку ниже, и вы сможете набирать текст так, как делаете это обычно, включая перенос строки.
- Для завершения набора и сохранения текстового файла нажмите сочетание клавиш Ctrl+Z, а затем — Enter. Это добавит отметку конца файла и сохранит его в текущей папке с указанным на 1-м шаге именем.
Создание текстового файла в PowerShell
PowerShell также имеет набор встроенных командлетов для сохранения текстовых данных в файл.
Out-File
Использование Out-File в PowerShell по своей функциональности сходно с оператором перенаправления вывода в командной строке. Вывод консоли перенаправляется в заданный файл.
Пример использования:
"Текстовая строка" | Out-File -FilePath .\file.txt
В этом примере в текущей папке PowerShell будет создан файл с именем file.txt и содержимым «Текстовая строка».
New-Item
Создание нового текстового файла в PowerShell возможно с помощью командлета New-Item. Пример команды, в которой создается текстовый файл file.txt, содержащий «Текстовая строка» в текущем расположении:
New-Item -Path . -Name "file.txt" -ItemType "file" -Value "Текстовая строка"
Set-Content и Add-Content
Ещё два командлета PowerShell для работы с текстовыми файлами:
- Set-Content — перезаписывает содержимое файла
- Add-Content — добавляет содержимое в конце выбранного файла
Их использование можно увидеть на примере следующей команды:
Add-Content -Path .\file.txt -Value "Ещё одна текстовая строка"
Вывод (чтение) текстового файла в командной строке и PowerShell
Теперь перейдем к способам просмотреть текстовые файлы в командной строке или PowerShell. Как и в предыдущем случае, учитывайте, что для файлов, содержащих кириллицу, возможны проблемы с отображением символов в правильной кодировке.
TYPE
Самый простой вариант — использование команды TYPE с указанием пути к файлу, который нужно отобразить в консоли, например:
type file.txt
MORE
Если файл объемный и содержит большое количество строк, используйте команду more, например:
more file.txt
Выполнив команду, вы увидите часть содержимого текста, которая помещается в окне консоли, далее вы можете использовать следующие клавиши:
- Enter — для отображения следующей строки файла.
- Пробел — для отображения следующих строк документа, которые поместятся в активное окно консоли.
- P — Показать следующие N строк. После нажатия этой клавиши с последующим указанием количества строк, будет выведено соответствующее количество строк текстового документа.
- S — пропустить следующие N строк, работает аналогично предыдущему варианту.
- Клавиша «=» — для отображения текущего номера строки.
- Q — для прекращения выполнения команды more.
Get-Content
Вывести содержимое текстового файла в PowerShell можно с помощью Get-Content с указанием пути к файлу, например:
Get-Content file.txt
Также вы можете выводить определенные строки файла, с помощью команд вида (вывод первых или последних 10 строк соответственно):
Get-Content file.txt | Select-Object -First 10 Get-Content file.txt | Select-Object -Last 10
Или присвоить содержимое файла переменной и вывести конкретную строку:
$file_text = Get-Content file.txt $file_text[2]
Помимо использования ручного ввода команд, вы можете использовать консольные текстовые редакторы — сторонние в версиях для Windows, такие как Vim, Nano, Kinesics Text Editor или даже старый встроенный edit.com (может отсутствовать в вашей версии системы и требовать патча NTVDMx64).