0

I am working on a programming assignment where I have to search for an entry in a text file, and print out text corresponding to the entry. As an example, let's say I have an entry as follows,

JOHN DOE

34 RIGHT WAY

HALIFAX

465-0394

, and the user enters HALIFAX as the keyword, I then would want to find the line that Halifax is located on, and then print out all associated text with this entry. The tricky part is doing this all without grep, sed, or awk, as the assignment is not accepted if these commands are used. I thought about using regular expressions, but these text manipulations can only be done on a single line, and I must do it for the entire file. As of now I am stumped and any help would be appreciated!

Alex

bmargulies
  • 97,814
  • 39
  • 186
  • 310

3 Answers3

1

You should read in the whole file in your bash script line by line and then check if the line contains your search term

cat $FILENAME | while read LINE
do
       if [[ $LINE =~ *HALIFAX* ]] then
          echo "I found HALIFAX"
       fi
done

From here on it should be easy enough for you to print out the rest.

sebs
  • 4,566
  • 3
  • 19
  • 28
  • If I were your teacher I'd pass you with a lower grade because of the [useless use of `cat`](http://partmaps.org/era/unix/award.html) here. – tripleee Jul 12 '13 at 03:26
0

I'm assuming this is bash scripting from the tag. My suggestion would be to read the text file line by line into an array, and then loop through the array, searching for the keyword in each string. This can be done using wild cards. Here's a link: String contains in Bash. Could you clarify "print out all associated text with this entry"?

Community
  • 1
  • 1
austin-schick
  • 1,225
  • 7
  • 11
0

You can do this by using while loop reading the file line by line.

#set the delimiter to newline
IFS_backup=$IFS
IFS=$'\n'

#variable to calculate line number
lineNum=0
while read a1
do
let "lineNum++" #increment variable for each line 

#variable a1 store the value of each line 

#do comparision with $a1 by user input string
#if string match then value of lineNum equal to the line number of file
# containing user input string

done<filename
Dinesh Subedi
  • 2,603
  • 1
  • 26
  • 36