Bryan Wong
Bryan Wong

Reputation: 633

How to format output using sed

I have a shell script and require your expertise on this.

 SearchAirline() {
echo "Enter Airline Name:"
read airlineName

if [ $? -eq 0 ];then
echo -e "\t\t\E[43;31;1mFlight Information\E[0m"
echo -e "Departure Time     Flight      Airlines    Vacancy"
echo "__________________________________________________________________________"

#cat flightlist.txt | grep $airlineName flightlist.txt
    old_IFS=$IFS 
    IFS=$'\n'
for LINE in `sed -e '$airlineName'  flightlist.txt`
    do
        print_flight $LINE
    done
  IFS=$old_IFS 
fi

}

It does not work to give me the filtered list. Instead, it prints the entire list.

Upvotes: 1

Views: 526

Answers (3)

Martin Ellis
Martin Ellis

Reputation: 9651

  • Change the '$airlineName' to "$airlineName". Variables aren't interpolated when they appear in single quotes.
  • Change the sed expression to only print lines that match:

    sed -n "/$airlineName/p"

Edit: Other answers suggest using other tools such as grep, and they might be right. The only reason my answer relates to sed is that your question asks for it specifically. I'm assuming you're expecting to do more significant processing with sed than what you've described in your question.

Upvotes: 2

Ed Morton
Ed Morton

Reputation: 204731

As @D.Shawley pointed out, this is REALLY a job for awk but that would mean rewriting the print_flight function too so here's a fixed shell script given some assumptions about your input file:

SearchAirline() {
   echo "Enter Airline Name:"
   read airlineName

   if [ $? -eq 0 ];then
      echo -e "\t\t\E[43;31;1mFlight Information\E[0m"
      echo -e "Departure Time     Flight      Airlines    Vacancy"
      echo "__________________________________________________________________________"

      grep "$airlineName" flightlist.txt |
      while IFS= read -r line
      do
         print_flight "$line"
      done
   fi
}

I strongly recommend you rewrite your script in awk though. If you'd like help with that, post another question and show us what print_flight looks like.

Upvotes: 0

D.Shawley
D.Shawley

Reputation: 59633

Add the -n option to your sed invocation:

-n

Suppress the default output (in which each line, after it is examined for editing, is written to standard output). Only lines explicitly selected for output are written.

Edit: You also have to use the correct quotes around $airlineName. Single quotes disable variable substitution. I credit Martin Ellis for this since I didn't notice it the first time.

BTW - I would highly recommend using awk for this sort of report. It can handle the formatting and selection and it will be a lot faster if you have a large data set.

Upvotes: 0

Related Questions