954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Read a file and store its contents in separate files according to data.

Hi

I am trying to write a script in Bash Shell. I have the file test.txt and has the following data:

AIR DR
[ 4] Pressure :50
AIR UR
[ 3] Pressure :70
WATER DR
[ 3] Pressure :90
[ 3] PIS: 402ps
WATER UR
[ 3] Pressure :110
[ 3] PIS: 402ps


Now i want to store each category's data in separate file.. For example :

AIR DR
[ 4] Pressure :50

in AIR DR.txt file

and simliarly the rest of the data in 3 other files.

I am able to read the file but I am not able to store them in different files.
Here is what I did to read the file:

while read line
do
 	echo $line >> line.txt
done <results.txt


Please help I am new to bash scripting!..

matharoo
Newbie Poster
13 posts since Feb 2010
Reputation Points: 10
Solved Threads: 0
 

You can use a case statement to get what you are after. For example:

#!/bin/bash

LOG=/dev/null

while read line; do
    case ${line} in
        'AIR DR')
        LOG='air_dr.out'
        ;;
        'AIR UR')
        LOG='air_ur.out'
        ;;
        'WATER DR')
        LOG='water_dr.out'
        ;;
        'WATER UR')
        LOG='water_ur.out'
        ;;
        *)
        echo ${line} >> ${LOG}
        ;;
    esac
done < results.txt
L7Sqr
Practically a Master Poster
657 posts since Feb 2011
Reputation Points: 201
Solved Threads: 124
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: