Alby
Alby

Reputation: 5752

piping bash input arguments in egrep's regular expression

here is the script that I am trying to run

#!/bin/bash

charlist=$1 #possible input:cat
wordlength=$2 #possible input: 3

cat ./nounlist | egrep \b[${charlist}]\b{${wordlength}}

output: nothing.# should've caught the following(using command line)

$ cat nounlist | egrep "\b[cat]{3}\b"
act
cat's_cradle
cat
cat-o'-nine-tails
cat's-paw
Sno-cat
act
act
act
act
rat-a-tat-tat
cat
cat's-claw
cat's_foot
cat's-ear
cat's-tail
cat's-ear
cat's_eye

basically I am trying to write a script that takes two arguments(wordlist, wordlength) and fetch all the words in the nounlist that consist of the char in the wordlist and has the length of wordlength variable. What I want to know is how to put bash variables in egrep's regular expression as strings?

Thanks!

Upvotes: 2

Views: 2672

Answers (1)

ruakh
ruakh

Reputation: 183484

You need to wrap the argument in double-quotes so that Bash doesn't try to handle the backslashes, and move the second \b to after the {${wordlength}}:

cat ./nounlist | egrep "\b[${charlist}]{${wordlength}}\b"

(If you run echo \b, you'll see that it just prints b. This is because Bash assumes that the \ is there to prevent b from having any special meaning; so it removes it.)

Upvotes: 3

Related Questions