Determine the File Count in Unix Directory

May 21, 2008

To determine the number of files in the Unix directory, use the following command.

CODE:
  1. ls -l | grep -c "^-.*"

Merging Files in Unix

May 9, 2008

You have multiple files in containing data in similar format and wanted to consolidate in a single file. This is usually the case if you have a daily log that you want to place an archive copy in a single file in weekly or in monthly, yearly.

The basic syntax of merging file is

CODE:
  1. cat <source file> >>  <target file>

If you have more than 10 files to merge it is better to write a shell script that will loop through the files and merge in a file. The following is the code for merging the files in a folder into a single file.

CODE:
  1. #!/bin/sh
  2. echo enter file name
  3. read filename
  4.  
  5. for arg in `ls;`
  6.    do
  7.    echo $arg
  8.    cat $arg >> $filename
  9. done

Lines 2 and 3 prompts the user for the filename of the file which will contain the consolidated contents of all the files in the current folder.

Lines 5 to 9 loops through the files in the current folder and merge the files to a single file.

Simplest File Merging

CODE:
  1. #!/bin/sh
  2. echo enter file name
  3. read source_filemask
  4. read master_filename
  5.  
  6. cat $arg >> $filename

A simple file merging

CODE:
  1. cat $<filemask>*> $<filename>

Example

CODE:
  1. cat $Test*> $FinalTest.txt

Writing Files in Unix

May 9, 2008

To write files in Unix, the syntax is

CODE:
  1. echo <text> > <filename>

Example

CODE:
  1. echo "This is my message." > myfile.txt

To add another line in the myfile.txt, use the following syntax.

CODE:
  1. echo "This is my second message." >>  myfile.txt

You may notice that double greater than sign (>>) is used instead of single greater than sign. This means that the message is written in append mode.

Let's open the myfile.txt by using the following command.

CODE:
  1. tail  myfile.txt

The content of the myfile.txt should have the following.

CODE:
  1. This is my message.
  2. This is my second message.