Saturday, 28 January 2012

cat

cat

catcan be used to openone or a group offiles , appendfiles into one file. one of the special functionality is to read an entire file line by line along with the read command. The examples will show us how.

Example 1)

/home/b3456/$ catbranches1.txt(Note: here /home/b3456/$ is the prompt

35467vdn/home/vd2

46788ghi/home/gh1/gh

89078bjk/home/vd2

/home/b3456/$ catbranches2.txt

56890lod/home/lod/inter

33456bhj/home/bhind

45790krk/myhome/krk

Combining these two files into a single file can be done by

/home/b3456/$ catbranches1.txtcatbranches2.txt

35467vdn/home/vd2

46788ghi/home/gh1/gh

89078bjk/home/vd2

56890lod/home/lod/inter

33456bhj/home/bhind

45790krk/myhome/krk

Or by

/home/b3456/$catbranches[1-2].txt

Suppose you have many such files named branches1.txt branches2.txt branches3.txt… branches<x>.txt where <x> is anysingle numeric or alphabetic character, you can use.

cat branches?.txt to open allthe files.

Example 2)

You want to write contents you have copied from a file into another file. one way to do it is to open it in a vi editor and then save it.

Other way to do it is by using cat to open a file and paste the contents.

/home/b3456/$ cat>filetocopy

#thesentence of these lines

were copied from a different file

andpasted here.

#the contents here were typed manually

^D

/home/b3456/$

/home/b3456/$morefiletocopy

#thesentence of these lines

were copied from a different file

andpasted here.

#the contents here were typed manually

/home/b3456/$

A^dcharacter(ctrl + d) must be typed at the end to mark the end of file.

If you already have a file with the same name and you want to append the contents copied into that file,

then use“>>”instead of‘>’

Example 3)

you can also use cat to read each line of a file into a variable, using read command.

Thiscannot be achieved with a ‘forin ’ loop since it considers words in a line as separate values assigned to the index variable.

The followingcommandswill tell youhow to achieve it using cat and read with a while loop.

Consider that you want toread the filebranches1.txt(example 1) ,in such a way that entire string ineach line is storedinto a variable and thenthat variableis used to extract each fields(separated by spaces)

/home/b3456/$ catbranches1.txt| while read line# the variable line stores the contents of a line

do

num=`echo $line|awk‘{print $1}’

path=` echo $line|awk‘{print $3}’

echo“$path isthe path for $num”

done

/home/vd2is the path for35467

/home/gh1/ghis the path for46788

/home/vd2 is the path for89078

The ‘for in’ loop imposes restrictions on the number of lines of a file which can beby it. But cat has no limitations. It can read any file, however large it is until the system resource is exhausted.