0

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!

3
  • You want to write the result to the file list? Commented May 21, 2019 at 10:08
  • Avoid the usage of egrep. This is depricated. Make use of grep -E instead. (see man grep) Commented May 21, 2019 at 12:55
  • Copy/paste your code to shellcheck.net, fix the issues it tells you about, and then let us know if you still have a problem you need help with. Commented May 21, 2019 at 18:38

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.