The CAT command in Linux is helpful in creating text files, displaying their contents, concatenating text from two or more text files into a new file. We can also append text from terminal to a file or append text to an existing file.

Create a new file

cat > newfile.txt

Concatenating multiple files to a new file

cat file1.txt file2.txt > newfile.txt

displays :

# Output:
# [Contents of file1.txt]
# [Contents of file2.txt]

Concatenate text from four files and save it in alphabetical order

We have four files we want to be concatenated in alphabetical order

cat file1.txt file2.txt file3.txt file4.txt

displays :

B from file1.txt
A from file2.txt
C from file4.txt
D from file3.txt
cat file1.txt file2.txt file3.txt file4.txt | sort > file5.txt
cat file5.txt 

will display :

A from file2.txt
B from file1.txt
C from file4.txt
D from file3.txt

Appending text from the Terminal to a file

cat >> term.txt

Appending text from one file to another

 cat file2.txt >> file1.txt

Displaying Line Numbers

to number all output lines we can use -n option :

cat -n file.txt

Suppress Repeated Empty Lines

If a file have unnecessary spacing, using the -s flag permits reducing multiple adjacent blank lines to a single blank line.

cat -s file.txt

The ‘tac’: Reverse ‘cat’

The tac command is the reverse of cat. It concatenates and displays files in reverse, starting from the last line and ending at the first line.

tac file.txt

Previous Post Next Post