A Pet
A Pet

Reputation: 1

numeric variable in egrep regular expression bash script

So I am trying to make a script that contains egrep and accepts a numeric variable

#!/bin/bash

var=$1
list="egrep "^.{$var}$ /usr/share/dict/words"
cat list

For example, if var is 5, I would like this script to print out every line with 5 characters. For some reason the script does not do that. Help would be greatly appreciated!

Upvotes: 0

Views: 60

Answers (1)

oguz ismail
oguz ismail

Reputation: 50795

Your script doesn't work because there are several problems with these lines:

list="egrep "^.{$var}$ /usr/share/dict/words"
cat list
  1. The first line isn't complete, it's missing a closing quote,
  2. Even if you fixed it, you're assigning a literal string to list, not the output of a command,
  3. RE and filename should be separated
  4. cat doesn't print a variable's content, echo does that.

So:

#!/bin/bash
var="$1"
list="$(egrep '^.{'"$var"'}$' /usr/share/dict/words)"
echo "$list"

should work.

Or even better, you can use just an command:

awk 'length==5' /usr/share/dict/words

with $1 or any other variable:

awk -v n="$1" 'length==n' /usr/share/dict/words

Upvotes: 3

Related Questions