Student Jack
Student Jack

Reputation: 1035

shell script of grep single line in bash script

I have a file with the following format:

123 2 3 48 85.64 85.95
Park ParkName Location
12 2.2 3.2 48 5.4 8.9

Now I could like to write a shell script to extract lines from this file. The first item from each line is a kind of flag. For different flags, I will make different process. See my code below:

head= ` echo "$line" | grep -P "^\d+" `    
if [ "$head" != "" ]; then  
 (do something...)  
fi  
head=` echo "$line" | grep -P "^[A-Z]+" `  
if [ "$head" != "" ]; then  
 (do something...)  
fi

The code works. But I dislike the complicated way of writing 2 "if". I would like to have something simple like:

if [ "$head" != "" ]; then  
 (do something...)  
elif [ "$head" != "" ]; then  
 (do something...)  
fi

Any thoughts?

Upvotes: 0

Views: 308

Answers (2)

Vasanta Koli
Vasanta Koli

Reputation: 411

How about this. I guess it would fulfill your requirement

file

123 2 3 48 85.64 85.95

Park ParkName Location

12 2.2 3.2 48 5.4 8.9

script.sh

while read line

do

echo $line | grep -qP "^\d+" && echo "Line starts with Numbers"    
echo $line | grep -qP "^[a-zA-Z]+" && echo "Line Starts with String"

done < file

Output:-

bash script.sh

Line starts with Numbers

Line Starts with String

Line starts with Numbers

Upvotes: 0

julumme
julumme

Reputation: 2366

How about pure bash solution? Bash has a built-in regexp functionality, that you trigger with ~ character. Be aware though that processing huge files with bash read line will not yield in optimal performance..

#!/bin/bash

file=$1

while read line
do
  echo "read [$line]"
  if [[ $line =~ ^[0-9] ]]; then
    echo '  Processing numeric line'

  elif [[ $line =~ ^[A-Za-z]  ]]; then
    echo '  Processing a text line'
  fi
done < $file

Upvotes: 1

Related Questions