Safin Mahmud
Safin Mahmud

Reputation: 17

How to find string that are in the end of the line in shell script using grep

I have a file where I am searching for numbers that are at the end of the line

Try and Trust, by Horatio Alger, Jr. 1

The Rover Boys at School, by Arthur M. Winfield 11

A Tramp Abroad, Part 1, by Mark Twain 23

if I search for 1, I want to print the first line where 1 is at the end of the line. Not the second line where there is 11, or the third line where 1 is in the middle of the sentence.

echo "Enter the content you are searching for:"  
    read foo

if x=$(grep -A 1 -i "$foo\$" GUTINDEX.ALL)
    then echo -e "$x"
fi

\$ is for detecting the end of the line but this is not working. Why?

Upvotes: 0

Views: 410

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84541

If you are trying to create a script that allows you to enter a regex (regular expression) as an argument (positional parameter), you can simply use the form

grep "$2" "$1"

where "$2" is the regular expression and "$1" the filename. You can also add any additional options for grep as desired (like -A 1 for one line of context after the match, etc..)

A short example would be:

#!/bin/bash

[ -z "$1" -o -z "$2" ] && {
    printf "error: insufficient input.\n"
    printf "usage: %s filename regex\n" "${0##*/}"
    exit 1
}

[ -r "$1" ] || {
    printf "error: file not readable '%s'\n" "$1"
    exit 2
}

grep "$2" "$1"

(note: there is no need to escape the '$' as it looses its special meaning when contained within a string -- expansion isn't performed -- so long as it is quoted)

Example Use/Output

$ bash parse.sh gutindex.all '[^0-9]1$'
Try and Trust, by Horatio Alger, Jr. 1

or

$ bash parse.sh gutindex.all '23$'
A Tramp Abroad, Part 1, by Mark Twain 23

There are a number of ways to approach this. Look it over and let me know if you have further questions.

Upvotes: 0

James Brown
James Brown

Reputation: 37394

With awk:

$ foo=1
$ awk -v s="$foo" '$NF==s' file
Try and Trust, by Horatio Alger, Jr. 1

Explained:

$ awk -v s="$foo" '  # the search term in s var
$NF==s               # if the last field is equal to s print the record
' file

Upvotes: 1

Related Questions