Cat command in windows

Is there replacement for cat on Windows

I need to join two binary files with a *.bat script on Windows.

How can I achieve that?

11 Answers 11

Windows type command works similarly to UNIX cat .

Example 1:

is equivalent of:

Example 2:

This command will merge all the vcards into one.

You can use copy /b like this:

If you have control over the machine where you’re doing your work, I highly recommend installing GnuWin32. Just «Download All» and let the wget program retrieve all the packages. You will then have access to cat, grep, find, gzip, tar, less, and hundreds of others.

GnuWin32 is one of the first things I install on a new Windows box.

600 kB exe incorporating

30 Unix utilities. The only difference is that one should use «busybox cat» command instead of simple «cat» – Fr0sT Jan 10 ’14 at 13:59

Shameless PowerShell plug (because I think the learning curve is a pain, so teaching something at any opportunity can help)

Note that type is an alias for Get-Content, so if you like it better, you can write:

Just use the dos copy command with multiple source files and one destination file.

You might need the /B option for binary files

In Windows 10’s Redstone 1 release, the Windows added a real Linux subsystem for the NTOS kernel. I think originally it was intended to support Android apps, and maybe docker type scenarios. Microsoft partnered with Canonical and added an actual native bash shell. Also, you can use the apt package manager to get many Ubuntu packages. For example, you can do apt-get gcc to install the GCC tool chain as you would on a Linux box.

If such a thing existed while I was in university, I think I could have done most of my Unix programming assignments in the native Windows bash shell.

If you simply want to append text to the end of existing file, you can use the >> pipe. ex:

If you have to use a batch script and have python installed here is a polygot answer in batch and python:

If saved as join.bat usage would be:

Thanks too this answer for the inspiration.

I try to rejoin tar archive which has been splitted in a Linux server.

Networking/Computing Tips/Tricks

What is the ‘cat’ command, and how can I use it?

The ‘cat’ [short for “concatenate“] command is one of the most frequently used commands in Linux and other operating systems. The cat command allows us to create single or multiple files, view contain of file, concatenate files and redirect output in terminal or files.

The command is available in Linux, Windows Power Shell, and MAC-OS.

Here is the Windows usage screen for cat:

Here is a Linux cat help screen:

We understand there are lots of options, now let’s look at some usage examples.

1. The most basic and repetitive use of cat is to display the contents of a file. If you are using Linux, the following example will show contents of /etc/passwd file:

2. You can use cat to create a simple file. Let’s create a file called ‘example1’:

Now simply enter the information you want in the file followed by the CTRL+D (hold down Ctrl Key and type ‘d‘) to exit. The information you typed will be written into the example1 file.

You can verify this using the following command:

3. We can take that a step further and view content of multiple files where ‘example1’ and ‘example2’ are files:

4. Another way to display multiple files is to use the ‘;’ between cat commands:

# cat example1; cat example2; cat example3

5. Sometimes the output of displaying a file runs off the screen. Managing how much information the cat command displays is simple. The cat command comes with the ability to control the screen output with ‘more’ or ‘less’:

One screen worth of the file will be shown at a time with the «More» word at the bottom. Just hit the space bar to display the next screen.

Читайте также:  Настройка числа процессоров windows 10

This time the «:» will be displayed. Just hit ‘Q’ to quit.

6. In the old days, line numbering was important in programming. Today, sometimes when helping someone find a particular item, it is helpful to have line numbers in the display. The cat command can use the ‘-n’ option to display line numbers:

7. You can use cat to redirect output from the terminal window (default output) to say another file. This is called the redirection operator. This is done with the ‘>‘ (greater than) symbol. Be careful here, as you may overwrite an existing file!!

Essentially we have created a copy of example1 in example3.

8. OK — so what is we had an existing example3 file and we wanted to append example1 contents onto example3? The cat command supports this with the ‘>>‘ (double greater than) symbol.

9. Taking that a step further, what is we wanted to send contents of multiple files and create a single file? The cat command does this as follows:

These files are added in order.

10. Taking that process even further, what if we wanted to do the same thing as #9 but this time sort the contents? The cat command can do this easily with piping to the ‘sort’ process:

11. OK — what if we wanted to create a file with some set of commands we use regularly and that as input? The cat command does this with the ‘ patron link where you will receive free bonus access to courses and more, or simply buying us a cup of coffee!, and all comments are welcome!

1″ :pagination=»pagination» :callback=»loadData» :options=»paginationOptions»>

The cat Command

cat is one of the most frequently used commands on Unix-like operating systems. It has three related functions with regard to text files: displaying them, combining copies of them and creating new ones.

cat’s general syntax is

The square brackets indicate that the enclosed items are optional.

Reading Files

The most common use of cat is to read the contents of files, and cat is often the most convenient program for this purpose. All that is necessary to open a text file for viewing on the display monitor is to type the word cat followed by a space and the name of the file and then press the ENTER key. For example, the following will display the contents of a file named file1:

The standard output (i.e., default destination of the output) for cat, as is generally the case for other command line (i.e., all-text mode) programs, is the monitor screen. However, it can be redirected from the screen, for example, to another file to be written to that file or to another command to use as the input for that command.

In the following example, the standard output of cat is redirected using the output redirection operator (which is represented by a rightward pointing angular bracket) to file2:

That is, the output from cat is written to file2 instead of being displayed on the monitor screen.

The standard output could instead be redirected using a pipe (represented by a vertical bar) to a filter (i.e., a program that transforms data in some meaningful way) for further processing. For example, if the file is too large for all of the text to fit on the monitor screen simultaneously, as is frequently the case, the text will scroll down the screen at high speed and be very difficult to read. This problem is easily solved by piping the output to the filter less, i.e.,

This allows the user to advance the contents of the file one screenful at a time by pressing the space bar and to move backwards by pressing the b key. The user can exit from less by pressing the q key.

The standard input (i.e., the default source of input data) for cat, as is generally the case for other commands on Unix-like systems, is the keyboard. That is, if no file is specified for it to open, cat will read whatever is typed in on the keyboard.

Читайте также:  Как завершить windows defender

Typing the command cat followed by the output redirection operator and a file name on the same line, pressing ENTER to move to the next line, then typing some text and finally pressing ENTER again causes the text to be written to that file. Thus, in the following example the text that is typed on the second line will be written to a file named felines:

cat > felines
This is not about a feline.

The program is terminated and the normal command prompt is restored by pressing the CONTROL and d keys simultaneously.

Repeating the above example without using a redirection operator and specifying a destination file, i.e.,

causes the text to be sent to standard output, i.e., to be repeated on the monitor screen.

Concatenation

The second role of cat is concatenation (i.e., stringing together) of copies of the contents of files. (This is the source of cat’s curious name.) Because the concatenation occurs only to the copies, there is no effect on the original files.

For example, the following command will concatenate copies of the contents of the three files file1, file2 and file3:

The contents of each file will be displayed on the monitor screen (which, again, is standard output, and thus the destination of the output in the absence of redirection) starting on a new line and in the order that the file names appear in the command. This output could just as easily be redirected using the output redirection operator to another file, such as file4, using the following:

cat file1 file2 file3 > file4

In the next example, the output of cat is piped to the sort filter in order to alphabetize the lines of text after concatenation and prior to writing to file4:

cat file1 file2 file3 | sort > file4

File Creation

The third use for cat is file creation. For small files this is often easier than using vi, gedit or other text editors. It is accomplished by typing cat followed by the output redirection operator and the name of the file to be created, then pressing ENTER and finally simultaneously pressing the CONTROL and d keys. For example, a new file named file1 can be created by typing

then pressing the ENTER key and finally simultaneously pressing the CONTROL and d keys.

If a file named file1 already exists, it will be overwritten (i.e., all of its contents will be erased) by the new, empty file with the same name. Thus the cautious user might prefer to instead use the append operator (represented by two successive rightward pointing angular brackets) in order to prevent unintended erasure. That is,

That is, if an attempt is made to create a file by using cat and the append operator, and the new file has the same name as an existing file, the existing file is, in fact, preserved rather than overwritten, and any new text is added to the end of the existing file.

Text can be entered at the time of file creation by typing it in after pressing the ENTER key. Any amount of text can be typed, including text on multiple lines.

cat can also be used to simultaneously create a new file and transfer to it the data from an existing file. This is accomplished by typing cat, the name of the file from which the output will come, the output redirection operator and the name of the file to be created. Then pressing ENTER causes the new file to be created and written to. For example, typing the following and then pressing ENTER creates a new file named file2 that contains a copy of the contents of file1:

There is no effect on the contents of file1. (The same thing can, of course, be accomplished just as easily using cp command, which is used to copy files, i.e., cp file1 file2, but the above example does illustrate the great versatility of cat.)

A slight modification to the above procedure makes it possible to create a new file and write text into it from both another file and the keyboard. A hyphen surrounded by spaces is added before the input file if the typed-in text is to come before the text from the input file, and it is added after the input file if the typed-in text is to go after the text from the input file. Thus, for example, to create a new file file6 that consists of text typed in from the keyboard followed by the contents of file5, first enter the following:

Читайте также:  Не работает разъем наушников спереди процессора windows 10

Or to create a new file file8 that consists of the contents of file7 followed by text typed in from the keyboard, first enter the following:

In either case, then press ENTER to move to a new line and type the desired text on any number of lines. Finally press ENTER once more followed by pressing the CONTROL and d keys simultaneously to execute (i.e., run) the command.

An example of a practical application for this use of cat is the creation of form letters (or other documents) for which only the top parts (e.g., dates and names) are customized for each recipient.

Created June 15, 2004. Updated April 10, 2005.
Copyright © 2004 — 2005 Bellevue Linux. All Rights Reserved.

Сответствие консольных команд Windows и Linux.

При переходе с Windows на Linux и наоборот, для тех, кто знаком с командной строкой, может пригодиться небольшая справка по соответствию консольных команд этих операционных систем. Естественно, полного соответствия, за редким исключением, не бывает, и в приведенной таблице собраны команды, идентичные по результатам выполнения или функционально близкие.

Соответствие команд CMD Windows командам Linux

Описание Команда CMD Windows Команда Linux
Вызов справочной системы HELP apropos, man, whatis
Вызов командного интерпретатора (оболочки) CMD bash, csh, sh
Очистка экрана CLS clear, reset
Вывод сообщения на экран ECHO echo
Пауза в работе PAUSE sleep
Настройка параметров терминала MODE stty
Установка значений переменных окружения (указание путей к каталогам) PATH, SET, SETx env, set
Изменение системной даты DATE date
Изменение системного времени TIME date
Выход из командной строки EXIT exit
Работа с файлами и каталогами
Отображение списка файлов и каталогов DIR dir, ls
Создание каталога MKDIR mkdir
Удаление каталога RMDIR rmdir
Удаление файла DEL, ERASE rm
Переход в другой каталог CD cd
Копирование файлов или каталогов COPY, XCOPY cp
Переименование файла REN, RENAME mv
Перемещение файлов MOVE mv
Поиск файла WHERE find, locate
Вывод на экран содержимого файла TYPE, MORE cat, less, more
Сравнение содержимого двух файлов COMP, FC cmp, diff, diff3, sdiff
Сортировка строк в текстовом файле SORT sort
Изменение атрибутов файла ATTRIB chmod
Создание символьной ссылки на файл или каталог MKLINK ln
Резервное копирование данных ROBOCOPY cpio, tar
Вызов текстового редактора EDIT (нет в Windows Vista и старше) vi
Работа с томами и разделами
Создание разделов FDISK fdisk
Управление разделами DISKPART parted, partx
Форматирование диска, создание файловой системы DISKPART, FORMAT mformat, mkfs
Проверка файловой системы CHKDSK fsck
Управление системой.
Отобразить список процессов TASKLIST, QUERY PROCESS ps
Уничтожить процесс TASKKILL kill, killall
Перезагрузить компьютер SHUTDOWN shutdown, reboot
Выключить компьютер SHUTDOWN shutdown, halt
Выполнить команду от имени другого пользователя RUNAS sudo
Отобразить имя компьютера HOSTNAME hostname
Пользователи и группы.
Создать нового пользователя NET USER useradd
Изменить параметры пользователя NET USER usermod
Изменить пароль пользователя NET USER passwd
Удалить пользователя NET USER userdel
Создать новую группу пользователей NET GROUP groupadd
Изменить параметры группы NET GROUP groupmod
Удалить группу NET GROUP groupdel
Отобразить список активных пользователей QUERY USER users
Работа с сетью.
Работа с таблицей соответствия IP и MAC адресов ARP arp arp
Конфигурация протокола IP IPCONFIG, NETSH ifconfig, ip
Работа с таблицей маршрутизации ROUTE route
Опрос узла по протоколу ICMP PING ping
Клиент Telnet TELNET telnet
Работа с DNS-сервером в интерактивном режиме NSLOOKUP dig, nslookup
Трассировка маршрута к удаленному узлу TRACERT traceroute
Отобразить статистику сетевых соединений NETSTAT netstat

Строчные и заглавные буквы для команд командной строки Windows воспринимаются одинаково, ECHO и echo — будет интерпретировано как одна и та же команда. При работе в командной строке Linux соблюдение регистра символов обязательно.

Если вы желаете помочь развитию проекта, можете воспользоваться кнопкой «Поделиться» для своей социальной сети

Оцените статью