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 *