0

I'm writing a bash script and I would like to print all lines containing a word, but only if it is at the end of a line. So given a file like this:

d41d8cd98f00b204e9800998ecf8427e  ./12/2.txt
d41d8cd98f00b204e9800998ecf8427e  ./12/1
d41d8cd98f00b204e9800998ecf8427e  ./12/1.txt
d41d8cd98f00b204e9800998ecf8427e  ./1
d41d8cd98f00b204e9800998ecf8427e  ./11.txt

and the given word equal to "./1" I would like to print only the line:

717c41ff4049b0e8cbdc7ec7e49ad021  ./1

I'd simply use grep, with "$" anchor added at the end, for that but my problem is that the words may contain dots so I need to have the -F option, but then I am unsure how to secure that the printed lines contain the word at the end of the line, as I can't use line anchors.

Edit: The word is passed as a variable not a fixed string.

madasionka
  • 812
  • 2
  • 10
  • 29

3 Answers3

2

You can also use awk if your definition of word means white-space separated as given in sample input

$ awk '$NF == "./1"' ip.txt 
d41d8cd98f00b204e9800998ecf8427e  ./1

This will print only those lines whose last field is exactly equal to string ./1

No need to worry about escaping regex meta characters if the search word changes


To pass shell variable:

$ s='./1'
$ awk -v word="$s" '$NF == word' ip.txt 
d41d8cd98f00b204e9800998ecf8427e  ./1

See also How do I use shell variables in an awk script?

Sundeep
  • 23,246
  • 2
  • 28
  • 103
1

You can use grep with this pattern:

grep '\./1$' file

d41d8cd98f00b204e9800998ecf8427e  ./1

\./1$ will match ./1 only at the end of line due to anchor $.


Based on comment below, if you want to pass search term using a variable:

s='./1'

awk -v s="$s" 'index($0, s) + length(s) -1 == length()' file

d41d8cd98f00b204e9800998ecf8427e  ./1

This will also work when search term is not separated by whitespaces

anubhava
  • 761,203
  • 64
  • 569
  • 643
-1

If the name you want to search for contains . you can escape them. e.g

bash-3.2$ NAME="./1"
bash-3.2$ grep "$(sed -e 's/[.]/[.]/g' <<< "$NAME")$" file
d41d8cd98f00b204e9800998ecf8427e  ./1
jq170727
  • 13,159
  • 3
  • 46
  • 56
  • 1
    I believe this answers the OP's question and offers a suggestion as to how the OP can transform the word they are searching for into an argument they can pass to `grep`. Anyone care to point out what's wrong with this answer? What did I miss? – jq170727 Sep 11 '17 at 08:25
  • When you want literal strings, use literal strings, don't try to disable all possible regexp metacharacters to try to make your regexp behave as if it were a string. – Ed Morton Sep 12 '17 at 01:42