1

I have a script that displays every file in a directory that has a filename containing 5 or less characters:

#!/bin/bash

ls | egrep '^.{0,5}$'

Example directory:

foobar
foo
bar

Output:

foo
bar

But when I try to use a variable in place of 5 like seen below, I get no output. No error, so I'm assuming it's still looking for some kind of range. But just not 0-5.

#!/bin/bash

declare -i num=5
ls | egrep '^.{0,$num}$'

How do I use a variable inside on the curly braces?

codeforester
  • 39,467
  • 16
  • 112
  • 140
qiterpot
  • 37
  • 5

3 Answers3

5

Curly braces are not the issue here, it is the single quotes. Use double quotes - variables inside '' are not expanded by shell:

ls | egrep "^.{0,$num}$"

See also:

Community
  • 1
  • 1
codeforester
  • 39,467
  • 16
  • 112
  • 140
1

Don't parse the output of ls; just use a pattern that matches everything except names with 6 or more characters:

shopt -s extglob
printf '%s\n' !(??????*)

If you need a variable length pattern, build it up with a loop:

pat=; for ((i=0; i<=$num; i++)); do pat+=?; done
printf '%s\n' !($pat*)

# POSIX-compatible variant
i=0
pat=?
while [ "$i" < "$num" ]; do
  printf '%s\n' $pat
  pat+=?
done

Or, match all files and filter them using regular expression matching.

for f in *; do
    [[ $f =~ ^.{0,$num}$ ]] || continue
    printf '%s\n' "$f"
done
codeforester
  • 39,467
  • 16
  • 112
  • 140
chepner
  • 497,756
  • 71
  • 530
  • 681
0
#/bin/sh
FIVE=5
ls | egrep "^.{0,${FIVE}}$"

You just needed to use quotation mark when using variables.

Mario
  • 679
  • 6
  • 10