0

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?

2
  • 1
    I'm surprised that your code works! How could head= echo "$line" | grep -P "^\d+" work? Commented Apr 7, 2014 at 7:09
  • head=` echo "$line" | grep -P "^\d+" ` @devnull --- first time to post questions... sorry Commented Apr 7, 2014 at 7:20

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

sorry @Vasanta Koli, your answer is absolutely correct. meanwhile, i can see here the code has a good sense of grammar. However, julumme answer that first. First come first served. I would like to vote to you, but I dont have enough reputation points here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.