Creating file(s) in Unix

There are 2 ways files can be created in Unix as follows –

Command 1 – touch 

It creates an empty file.  A 0-byte file will be created with this command

E.g. –

$ touch emptyFile1

emptyFile1 will be created with 0-byte size.

Generally, when there is a need for creating multiple empty files, this command is useful.

$ touch emptyFile2 emptyFile3 emptyFile4

emptyFile2, emptyFile3, emptyFile4 will be created with 0 byte size.

Command 2 – cat

cat command can be used in the following ways to create a file –

A. It creates a file with a few lines in it. 

E.g. –

$ cat > sampleFile   now press Enter

Test line 1 for sampleFile

Test line 2 for sampleFile.  Now press Ctrl + d

sampleFile will be created with 2 lines as mentioned above.

Note – Ctrl + d indicates EOF (end of file) character in Unix.

B. It concatenates the contents of 2 files and stores them in 3rd file 

E.g. –

$ cat > sampleFile1 sampleFile2 > newFile   now press Enter

newFile will be created contents of sampleFile1 followed by contents of sampleFile2

* Note: In case newFile already had contents, then it would be overwritten.

C. It concatenates the contents of 2 files and stores them in 3rd file without overwriting the contents of 3rd file

E.g. –

$ cat > sampleFile1 sampleFile2 >> newFile   now press Enter

newFile contents will be appended with contents of sampleFile1 followed by contents of sampleFile2

Show 4 Comments

4 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *