Share to: share facebook share twitter share wa share telegram print page

Cat (Unix)

cat
Original author(s)Ken Thompson,
Dennis Ritchie
Developer(s)AT&T Bell Laboratories
Initial releaseNovember 3, 1971; 52 years ago (1971-11-03)
Operating systemUnix, Unix-like, Plan 9, Inferno, ReactOS
PlatformCross-platform
TypeCommand
Licensecoreutils: GPLv3+
ReactOS: GPLv2+

cat is a standard Unix utility that reads files sequentially, writing them to standard output. The name is derived from its function to (con)catenate files (from Latin catenare, "to chain").[1] [2] It has been ported to a number of operating systems.

The other primary purpose of cat, aside from concatenation, is file printing — allowing the computer user to view the contents of a file. Printing to files and the terminal are the most common uses of cat.[3]

History

cat was part of the early versions of Unix, e.g., Version 1, and replaced pr, a PDP-7 and Multics utility for copying a single file to the screen.[4] It was written by Ken Thompson and Dennis Ritchie. The version of cat bundled in GNU coreutils was written by Torbjorn Granlund and Richard Stallman.[5] The ReactOS version was written by David Welch, Semyon Novikov, and Hermès Bélusca.[6]

Over time, alternative utilities such as tac and bat also became available, bringing different new features.[7][8]

Usage

The cat utility serves a dual purpose: concatenating and printing. With a single argument, it is often used to print a file to the user's terminal emulator (or historically to a computer terminal or teletype). With more than one argument, it concatenates several files. The combined result is by default also printed to the terminal, but often users redirect the result into yet another file.[9] Hence printing a single file to the terminal is a special use-case of this concatenation program. Yet, this is its most common use.[3]

The Single Unix Specification defines the operation of cat to read files in the sequence given in its arguments, writing their contents to the standard output in the same sequence. The specification mandates the support of one option flag, u for unbuffered output, meaning that each byte is written after it has been read. Some operating systems, like the ones using GNU Core Utilities, do this by default and ignore the flag.[10]

If one of the input filenames is specified as a single hyphen (-), then cat reads from standard input at that point in the sequence. If no files are specified, cat reads from standard input only.

The command-syntax is:

cat [options] [file_names]

Options

Example of some cat options:[11]

  • -b (GNU: --number-nonblank), number non-blank output lines
  • -e implies -v but also display end-of-line characters as $ (GNU only: -E the same, but without implying -v)
  • -n (GNU: --number), number all output lines
  • -s (GNU: --squeeze-blank), squeeze multiple adjacent blank lines
  • -t implies -v, but also display tabs as ^I (GNU: -T the same, but without implying -v)
  • -u use unbuffered I/O for stdout. POSIX does not specify the behavior without this option.
  • -v (GNU: --show-nonprinting), displays nonprinting characters, except for tabs and the end of line character

Use cases

cat can be used to pipe a file to a program that expects plain text or binary data on its input stream. cat does not destroy non-text bytes when concatenating and outputting. As such, its two main use cases are text files and certain format-compatible types of binary files.

Concatenation of text is limited to text files using the same legacy encoding, such as ASCII. cat does not provide a way to concatenate Unicode text files that have a Byte Order Mark or files using different text encodings from each other.

For many structured binary data sets, the resulting combined file may not be valid; for example, if a file has a unique header or footer, the result will spuriously duplicate these. However, for some multimedia digital container formats, the resulting file is valid, and so cat provides an effective means of appending files. Video streams can be a significant example of files that cat can concatenate without issue, e.g. the MPEG program stream (MPEG-1 and MPEG-2) and DV (Digital Video) formats, which are fundamentally simple streams of packets.

Examples

Command Explanation
cat file1.txt Display contents of file
cat file1.txt file2.txt Concatenate two text files and display the result in the terminal
cat file1.txt file2.txt > newcombinedfile.txt Concatenate two text files and write them to a new file
cat >newfile.txt Create a file called newfile.txt. Type the desired input and press CTRL+D to finish. The text will be in file newfile.txt.
cat -n file1.txt file2.txt > newnumberedfile.txt Some implementations of cat, with option -n, can also number lines
cat file1.txt > file2.txt Copy the contents of file1.txt into file2.txt
cat file1.txt >> file2.txt Append the contents of file1.txt to file2.txt
cat file1.txt file2.txt file3.txt | sort > test4 Concatenate the files, sort the complete set of lines, and write the output to a newly created file
cat file1.txt file2.txt | less Run the program "less" with the concatenation of file1 and file2 as its input
cat file1.txt | grep example Highlight instances the word "example" in file1.txt
command | cat Cancel "command" special behavior (e.g. paging) when it writes directly to TTY (cf. UUOC below)

Unix culture

Jargon file definition

The Jargon File version 4.4.7 lists this as the definition of cat:

  1. To spew an entire file to the screen or some other output sink without pause (syn. blast).
  2. By extension, to dump large amounts of data at an unprepared target or with no intention of browsing it carefully. Usage: considered silly. Rare outside Unix sites. See also dd, BLT.

Among Unix fans, cat(1) is considered an excellent example of user-interface design, because it delivers the file contents without such verbosity as spacing or headers between the files, and because it does not require the files to consist of lines of text, but works with any sort of data.

Among Unix critics, cat(1) is considered the canonical example of bad user-interface design, because of its woefully unobvious name. It is far more often used to blast a single file to standard output than to concatenate two or more files. The name cat for the former operation is just as unintuitive as, say, LISP's cdr.[citation needed]

Useless use of cat

Useless use of cat (UUOC) is common Unix jargon for command line constructs that only provide a function of convenience to the user.[12] In computing, the word "abuse",[13] in the second sense of the definition, is used to disparage the excessive or unnecessary use of a language construct; thus, abuse of cat is sometimes called "cat abuse". Example of a common cat abuse is given in the award:

cat filename | command arg1 arg2 argn

This can be rewritten using redirection of stdin instead, in either of the following forms (the first is more traditional):

command arg1 arg2 argn < filename
<filename command arg1 arg2 argn

Beyond other benefits, the input redirection forms allow command to perform random access on the file, whereas the cat examples do not. This is because the redirection form opens the file as the stdin file descriptor which command can fully access, while the cat form simply provides the data as a stream of bytes.

Another common case where cat is unnecessary is where a command defaults to operating on stdin, but will read from a file, if the filename is given as an argument. This is the case for many common commands; the following examples

cat file | grep pattern
cat file | less

can instead be written as

grep pattern file
less file

A common interactive use of cat for a single file is to output the content of a file to standard output. However, if the output is piped or redirected, cat is unnecessary.

A cat written with UUOC might still be preferred for readability reasons, as reading a piped stream left-to-right might be easier to conceptualize.[14] Also, one wrong use of the redirection symbol > instead of < (often adjacent on keyboards) may permanently delete the content of a file, in other words clobbering, and one way to avoid this is to use cat with pipes. Compare:

command < in | command2 > out
<in command | command2 > out

with:

cat in | command | command2 > out

See also

  • paste
  • split, a command that splits a file into pieces which cat can then rejoin.
  • zcat
  • less
  • netcat – Computer networking utility

References

  1. ^ "In Unix, what do some obscurely named commands stand for?". University Information Technology Services. Indiana University.
  2. ^ Kernighan, Brian W.; Pike, Rob (1984). The UNIX Programming Environment. Addison-Wesley. p. 15.
  3. ^ a b Pike, Rob; Kernighan, Brian W. Program design in the UNIX environment (PDF) (Report). p. 3.
  4. ^ McIlroy, M. D. (1987). A Research Unix reader: annotated excerpts from the Programmer's Manual, 1971–1986 (PDF) (Technical report). CSTR. Bell Labs. 139.
  5. ^ cat(1) – Linux User Commands Manual
  6. ^ "reactos/cat.c at master · reactos/reactos · GitHub". github.com. Retrieved August 28, 2021.
  7. ^ "tac(1) - Linux manual page". man7.org.
  8. ^ "sharkdp/bat". December 2, 2021 – via GitHub.
  9. ^ UNIX programmers manual (PDF). bitsavers.org (Report). November 3, 1971. p. 32. Archived from the original (PDF) on 2006-06-17.
  10. ^ GNU Coreutils. "GNU Coreutils manual", GNU, Retrieved on 1 Mars 2017.
  11. ^ OpenBSD manual page and the GNU Core Utiltites version of cat
  12. ^ Brian Blackmore (1994-12-05). "Perl or Sed?". Newsgroupcomp.unix.shell. Retrieved 2024-02-12.
  13. ^ "Merriam Webster's Definition of Abuse". Retrieved 2021-02-25.
  14. ^ Nguyen, Dan. "Stanford Computational Journalism Lab". stanford.edu. Retrieved 2017-10-08.

Read other articles:

Pos

Kumpulan kotak pos di Inkpen Post Box Museum, dekat Taunton, Somerset Pos adalah bagian dari sistem pos yaitu sebuah metode yang digunakan untuk mengirimkan informasi atau suatu objek, di mana untuk dokumen tertulis biasanya dikirimkan dengan amplop tertutup atau berupa paket untuk benda-benda yang lain, pengirimannya mampu menjangkau seluruh wilayah di dunia. Pada dasarnya, sistem pelayanan pos bisa dilakukan oleh public ataupun private. Namun, sejak pertengahan abad ke 19, sistem per-pos-an...

Sagrada Familia, circa 1490, Musée des Beaux-Arts, Lyon. El Concierto, circa 1490, National Gallery, Londres. Lorenzo di Ottavio Costa (Ferrara, 1460 - Mantua, 5 de marzo de 1535) fue un pintor renacentista italiano. Aunque nació en Ferrara, su actividad artística la desarrolló en la ciudad de Bolonia. Biografía Fue hijo de un ignoto pintor, Giovanni Battista Costa, aunque parece que recibió su primera formación como artista en el taller de Ercole de' Roberti. A comienzos de la década...

Бажання прийняти у себе Паралімпійські та Олімпійські ігри 2010 висловили три міста. 2 липня 2003 року МОК оголосив столицю на своїй черговій сесії. Нею стала столиця Британської Колумбії — Ванкувер. Зміст 1 Процес виборів 1.1 Оцінювання 1.2 Вибори 1.2.1 Результати голос

Horst Ludwig StörmerHorst Ludwig StörmerLahir6 April 1949 (umur 74)Frankfurt, JermanKebangsaanJermanDikenal atasEfek quantum HallPenghargaanPenghargaan Nobel dalam Fisika (1998)Karier ilmiahBidangFisika Horst Ludwig Störmer (lahir 6 April 1949) adalah fisikawan Jerman yang menerima Hadiah Nobel Fisika bersama Daniel Tsui dan Robert Laughlin. Mereka bertiga menerima penghargaan itu untuk penemuan mereka pada fluida kuantum bentuk baru dengan eksitasi yang dipancarkan secara fraksional ...

English painter Charles Allston Collins by John Everett Millais in 1850 Convent Thoughts (1850–51; Ashmolean Museum, Oxford) Charles Allston Collins (London 25 January 1828 – 9 April 1873) was a British painter, writer, and illustrator associated with the Pre-Raphaelite Brotherhood. Life and work Early years Collins was born in Hampstead, north London, the son of landscape and genre painter William Collins. His older brother was the novelist Wilkie Collins. He was educated at Ston...

Jangan MarahAlbum studio karya Trio Kwek KwekDirilis16 Agustus 1995GenrePopLabelIdeal RecordMusica Studio'sKronologi Trio Kwek Kwek Semua Oke(1994)Semua Oke1994 Jangan Marah (1995) Tanteku(1996)Tanteku1996 Jangan Marah adalah album musik ketiga karya Trio Kwek Kwek yang dirilis pada tahun 1995. Berisi 10 buah lagu dengan lagu berjudul sama dengan album, Jangan Marah sebagai lagu utama album ini.[1] Daftar lagu Judul lagu Pencipta Jangan Marah Papa T Bob Sapi Sapiku Om Faizal Ke Pe...

العلاقات البرتغالية الإيطالية البرتغال إيطاليا   البرتغال   إيطاليا تعديل مصدري - تعديل   العلاقات البرتغالية الإيطالية هي العلاقات الثنائية التي تجمع بين البرتغال وإيطاليا.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين: و...

الدوري الهولندي الممتاز تفاصيل الموسم 1957-1958 النسخة 2  البلد هولندا  التاريخ بداية:25 أغسطس 1957  نهاية:4 يونيو 1958  المنظم الاتحاد الملكي الهولندي لكرة القدم  البطل في في دوس مباريات ملعوبة 306   عدد المشاركين 18   أهداف مسجلة 1135   1956-1957 1958-1959 تعديل مصدري - تعديل ...

Persuasions of the Witch's Craft The first edition cover of the bookAuthorTanya LuhrmannCountryUnited StatesLanguageEnglishSubjectAnthropology of religionPagan studiesPublisherHarvard University PressPublication date1989Media typePrint (Hardcover & Paperback)Pages382 Persuasions of the Witches' Craft: Ritual Magic in Contemporary England is a study of several Wiccan and ceremonial magic groups that assembled in southern England during the 1980s. It was written by the American anthrop...

2010 IAAF WorldIndoor ChampionshipsTrack events60 mmenwomen400 mmenwomen800 mmenwomen1500 mmenwomen3000 mmenwomen60 m hurdlesmenwomen4 × 400 m relaymenwomenField eventsHigh jumpmenwomenPole vaultmenwomenLong jumpmenwomenTriple jumpmenwomenShot putmenwomenCombined eventsPentathlonwomenHeptathlonmenvte The men's 800 metres at the 2010 IAAF World Indoor Championships was held at the ASPIRE Dome on 12, 13 and 14 March. Medalists Gold Silver Bronze Abubaker Kaki Sudan Boaz Kiplagat Lalan...

Municipality in Nuevo León, MexicoArramberri, Nuevo León Santa María de los Angeles de Río BlancoMunicipalityCoordinates: 24°06′N 99°49′W / 24.100°N 99.817°W / 24.100; -99.817CountryMexicoStateNuevo LeónFounded1626Government • TypeMunicipality • MayorArturo Alemán MartínezArea • Total2,809 km2 (1,085 sq mi)Population (2005) • Total14,692Time zoneUTC-6 (CST) • Summer (DST)UTC-...

Abidjan-Niger-Bahn Strecke der Abidjan-Niger-BahnStreckenlänge:ca. 1.150 kmSpurweite:1000 mm (Meterspur) Legende 0 Port-Bouët 6 m Treichville 1 m Pont Félix-Houphouët-Boigny (über Ébrié-Lagune) Abidjan-Lagune 10 m Anyama 82 m Agboville 32 m Eisenbahnbrücke Dimbokro (über N’Zi) Dimbokro 114 m Bouaké 312 m Katiola 326 m Tafiré 402 m Kouroukouna 374 m Ferkessédougou 332 m Ouangolodougou 328 m 617 Elfenbeinküste/Burkina Faso 297 m Niangoloko 337 m Banfora 320 m Bobo-Dioul...

This article may require cleanup to meet Wikipedia's quality standards. The specific problem is: Needs cleanup per WP:NOTTVGUIDE. Please help improve this article if you can. (November 2023) (Learn how and when to remove this template message) This article may need to be rewritten to comply with Wikipedia's quality standards. You can help. The talk page may contain suggestions. (November 2023) As Television Broadcasts Limited (TVB) is Hong Kong's largest television station, the television pro...

В Википедии есть статьи о других людях с такой фамилией, см. Смирнов; Смирнов, Сергей. Сергей Григорьевич Смирнов Дата рождения 20 октября 1902(1902-10-20) Место рождения Томск, Российская империя Дата смерти 15 октября 1943(1943-10-15) (40 лет) Место смерти Черниговская область, Украи...

Insides of a slip-stick piezoelectric motor. Two piezoelectric crystals are visible that provide the mechanical torque.[1] A piezoelectric motor or piezo motor is a type of electric motor based on the change in shape of a piezoelectric material when an electric field is applied, as a consequence of the converse piezoelectric effect. An electrical circuit makes acoustic or ultrasonic vibrations in the piezoelectric material, most often lead zirconate titanate and occasionally lithium n...

Port for naval ships and other assets This article is about the military installation. For the suburb of Perth, see Naval Base, Western Australia. This article relies largely or entirely on a single source. Relevant discussion may be found on the talk page. Please help improve this article by introducing citations to additional sources.Find sources: Naval base – news · newspapers · books · scholar · JSTOR (November 2023) French Navy ships at Réunion: ...

Khatun of Mongols ChabiPortrait by Araniko, displaying the characteristic gugu hatKhatun of MongolsTenure1260–1281PredecessorKhutughtai khatunSuccessorEmpress NambuiEmpress consort of the Yuan dynastyTenure1271–1281PredecessorEmpress QuanSuccessorEmpress NambuiBornJanuary 28, 1216Died20 March 1281(1281-03-20) (aged 65)SpouseKublai Khan (?-1281)IssueGrand Princess of Zhao, Yuelie Grand Princess of Chang, Ulujin Princess-Aunt of the State of Chang, Chalun Crown Prince Zhenjin, Prince o...

War between Rome and Carthage, 218 to 202 BC Second Punic WarPart of the Punic WarsThe western Mediterranean in 218 BCDateSpring 218 – 201 BC (17 years)LocationWestern MediterraneanResult Roman victoryTerritorialchanges Roman conquest of Carthaginian IberiaCarthaginian African territories reducedBelligerents Rome Eastern Numidia Syracuse (218–215 BC) Others Carthage Syracuse (214–212 BC) Western Numidia Others Commanders and leaders Scipio Africanus Fabius Cunctator Publius Corneli...

A cortical minicolumn (also called cortical microcolumn[1]) is a vertical column through the cortical layers of the brain. Neurons within the microcolumn receive common inputs, have common outputs, are interconnected, and may well constitute a fundamental computational unit of the cerebral cortex.[2][3] Minicolumns comprise perhaps 80–120 neurons, except in the primate primary visual cortex (V1), where there are typically more than twice the number. There are abo...

  关于名為陳勇的其他人物,請見「陳勇」。 陳勇진용(Jin Yong)基本資料代表國家/地區 韩国出生 (2003-04-08) 2003年4月8日(20歲)[1]身高1.70米(5英尺7英寸)[2]主項:男子單打、男子双打、混合双打職業戰績53勝–10負(男單)82勝–20負(男雙)11勝–8負(混雙)最高世界排名第36位(男雙-羅星升)(2023年6月27日[3])現時世界排名第36位(男雙-羅星...

Kembali kehalaman sebelumnya