====== BASH - Files - Parse a line from a file ======
There are many ways of doing this, depending on your needs.
----
===== Method 1 =====
Example file:
07/17 21:04:01 sndc addr unit 1 : hu P1 (TempLinc)
07/17 21:04:02 sndc func StatusReq : hc P
07/17 21:04:04 rcvi addr unit 15 : hu P15 (TempAck_5)
07/17 21:04:04 rcvi func Preset : level 11
07/17 21:04:04 Temperature = 78 : hu P0 (office_temp)
07/17 21:19:01 sndc addr unit 1 : hu P1 (TempLinc)
07/17 21:19:02 sndc func StatusReq : hc P
07/17 21:19:05 rcvi addr unit 15 : hu P15 (TempAck_5)
07/17 21:19:05 rcvi func Preset : level 11
07/17 21:19:05 Temperature = 78 : hu P0 (office_temp)
#!/bin/bash
fil=/home/test.log
# Test for existence of the test file
if [ -f $fil ]
then
# Read through the file looking for the word Temperature =
while read line
do
echo $line | grep -q Temperature
if [ $? == 0 ]; then
mytemp=`echo $line | cut -d = -f2 | cut -d : -f1`
echo "Current temperature is: $mytemp"
fi
done < $fil
fi
returns:
Current temperature is: 78
Current temperature is: 78
**NOTE:** The **-f** tests that the file exists.
Other options include:
* **-b file**: Checks if file is a block special file; if yes, then the condition becomes true. [ -b $file ].
* **-c file**: Checks if file is a character special file; if yes, then the condition becomes true. [ -c $file ].
* **-d file**: Checks if file is a directory; if yes, then the condition becomes true. [ -d $file ].
* **-e file**: Checks if file exists; is true even if file is a directory but exists. [ -e $file ].
* **-f file**: Checks if file is an ordinary file as opposed to a directory or special file; if yes, then the condition becomes true. [ -f $file ].
* **-g file**: Checks if file has its set group ID (SGID) bit set; if yes, then the condition becomes true. [ -g $file ].
* **-k file**: Checks if file has its sticky bit set; if yes, then the condition becomes true. [ -k $file ].
* **-p file**: Checks if file is a named pipe; if yes, then the condition becomes true. [ -p $file ].
* **-r file**: Checks if file is readable; if yes, then the condition becomes true. [ -r $file ].
* **-t file**: Checks if file descriptor is open and associated with a terminal; if yes, then the condition becomes true. [ -t $file ].
* **-s file**: Checks if file has size greater than 0; if yes, then condition becomes true. [ -s $file ].
* **-u file**: Checks if file has its Set User ID (SUID) bit set; if yes, then the condition becomes true. [ -u $file ].
* **-w file**: Checks if file is writable; if yes, then the condition becomes true. [ -w $file ].
* **-x file**: Checks if file is executable; if yes, then the condition becomes true. [ -x $file ].
----
===== Only get last temperature record =====
#!/bin/bash
fil=/home/temp.log.ttyS0
if [ -f $fil ]
then
mytemp=`grep Temperature $fil | tail -1 | cut -d = -f2 | cut -d : -f1`
echo "Current temperature is: $mytemp"
fi