sarcon
sarcon

Reputation: 23

grep - pattern as variable

file name: Data.txt

Inside this file:

...
3754  Skype Helper    
375  Skype Helper    
37  Skype
... 

file name: shell.sh

#!/bin/bash

IFS='
'
var="Skype"

grep "\d\+\s\+${var}$" /Users/run/Documents/Data.txt >> /Users/run/Documents/output.txt 

The output should be:

37  Skype

but

I get:

3754  Skype Helper    
375  Skype Helper    
37  Skype 

Thanks a lot

Upvotes: 2

Views: 537

Answers (2)

sarcon
sarcon

Reputation: 23

i work on a mac (macOS high sierra) and i CAN'T get the output I am looking for. I would appreciate so much if somebody try the first both files on my first posting but with the pattern from @Wiktor Stribiżew:

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You are using a BRE POSIX pattern that does not support PCRE (Perl-like) \d and \s, you may replace \d with [0-9] bracket expression and \s with [[:space:]] POSIX character class:

grep "[0-9]\+[[:space:]]\+${var}\$"

Note you may escape the last $ to make it an explicit literal dollar symbol, but it is not necessary as the trailing dollar is correctly parsed as the end of string symbol, and this will work, too:

grep "[0-9]\+[[:space:]]\+${var}$"

If you do not want to overescape, you may make the pattern POSIX ERE compatible:

grep -E "[0-9]+[[:space:]]+${var}$"
     ^^

You may actually keep on using \d and \s if you tell grep to use a PCRE regex engine to parse the pattern:

grep -P "\d+\s+${var}$"
     ^^

See the online demo.

Upvotes: 1

Related Questions