Vril dox
Vril dox

Reputation: 13

Sed not pattern matching

I have a directory with these files in it:

abc12345abc
abc1234567abc
abc123456789abc

I want to grab the file that has 7 numerals in it. I need to do this using sed via the pipe. I thought this would work:

ls -l | sed -n '/[0-9]\{7\}/p'

It returns:

abc1234567abc
abc123456789abc

Upvotes: 1

Views: 706

Answers (4)

potong
potong

Reputation: 58578

This might work for you (GNU sed):

sed '/[0-9]\{7\}/!d;/[0-9]\{8\}/d' file

If there are not 7 consecutive digits or there are more, delete the line.

Upvotes: 0

SiegeX
SiegeX

Reputation: 140537

First rule of scripting, don't parse ls

If you are trying to match files in a directory, use find, that's what it's meant for

find dir/ -regextype posix-extended -type f \
   -regex ".*[^[:digit:]][[:digit:]]{7}[^[:digit:]].*"

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627507

You want to match seven digits that are not enclosed with another digit.

You may use

sed -En '/(^|[^0-9])[0-9]{7}($|[^0-9])/p'

See the online demo.

Details

  • -E - enables POSIX ERE syntax (now, there is no need to escape {x} interval quantifiers)
  • (^|[^0-9]) - start of string or a non-digit char
  • [0-9]{7} - seven digits
  • ($|[^0-9]) - end of string or a non-digit char.

Upvotes: 1

chepner
chepner

Reputation: 532398

Regular expressions aren't anchored. abc123456789abc has a string of exactly 7 digits, 3 of them in fact: 1234567, 2345678, and 3456789. If you want the file names that don't have any longer matches, you need to check for non-digits before and after.

sed -n '/[^0-9][0-9]{7}[^0-9]/p'

Upvotes: 2

Related Questions