How to use cat utilty in Linux

cat is a standard Unix utility that reads files sequentially, writing them to standard output. cat (short for “concatenate“) command is one of the most frequently used command in Linux/Unix like operating systems. It allow us to create single or multiple files view contain in file..

Uses of cat command

Task: user “nitin” have created 1 new file “file1” in his home directory now how can he access this file with the use of cat utility.

$ cat file1

output:

1

(relative path to access the file. this will work only if you & the file both are at same place)

Command:

$ cat /home/nitin/file1

output:

4

(absolute path. this will always work if you have the permissions to access the file)

$ cat $HOME/file1

output:

5

($HOME variable will get substituted by value “/home/nitin”)

$ cat $PWD/Sample/Sample/file1

output:

6

($PWD variable will get substituted by value “/home/nitin”)

$ cat ~/Sample/Sample/file1

output:

7

(~ abbreviation will get expanded to value “/home/nitin”)

$ cat ~nitin/Sample/Sample/file1

output:

8

(~nitin means home dir of nitin that is “/home/nitin”)

Command:

$ cat . /Sample/Sample/file1

Output:

9

( . denotes current working directory which in our case is “/home/nitin”).

Now we got 2 files “file1” , “file2”.  and needs to put contents in both files to 3rd file “file3” and also needs to count the no. of users logged in.

Command:

$ cat file1 file2 > file3

Output:

1

(we are redirecting (> is redirection symbol) the output to “file3” instead of screen)

Command:

$ who | wc -l

Output:

2

(“who” display information about each user on separate line & “wc -l” counts no. of lines. Now most critical thing is to understand that when we should use redirection symbol (“>”, “|”).

requirement                                       symbol                                                                                   example

sending output to a <command>          |                                                                              who | wc -l, cal 2010 |more

sending output to a <file>                    >                                                                                    cat file1 file2 >file3

$ who | wc -l > users

10

(we are chaining the commands to get some useful information. Here we are redirecting the output

to “wc -l” command ( using “|”) & sending the result to file “users” (using “>”)).

$ cat file1 file2 | tee file4

11

 

We have seen multiple ways to access the content of files with the use of cat utility with different parameters.

Leave a Reply

Your email address will not be published.