user3211189
user3211189

Reputation: 69

Unix Command to Output Line Containing between digits

My question is a command (like grep, awk) that will output lines containing numbers between 3 & 8 digits.

I understand how to match between numbers like matching between 25 & 39 [2-3][5-9], but I don't understand how to output lines containing between a certain number of digits.


Input:

1234567
1234 
abc
1234567890
1
1AB2345C

Output:

1234567
1234 
1AB2345C

Upvotes: 1

Views: 83

Answers (2)

Thor
Thor

Reputation: 47099

You could do this by deleting all non-digits and then check line-length, e.g. here with tr and awk:

<infile tr -cd '0-9\n' | awk 'length >= 3 && length <= 8'

Output:

1234567
1234
12345

Upvotes: 0

Kent
Kent

Reputation: 195049

This awk one-liner does it:

awk '{s=$0}{n=gsub(/[0-9]/,"",s)}n>=3&&n<=8' file

test with your example:

kent$  echo "1234567
1234 
abc
1234567890
1
1AB2345C"|awk '{s=$0}{n=gsub(/[0-9]/,"",s)}n>=3&&n<=8' 
1234567
1234 
1AB2345C

Explanation

awk                   #awk is a cli powerful text processing tool
'{s=$0}               #read one line, assign to variable s,(leave $0 untouched)
{n=gsub(/[0-9]/,"",s)}#replace all numbers of s to empty,
                      #return the count of replacement was done, assign it to n
n>=3&&n<=8'           #if n between 3 and 8, print the line ($0)

if the explanation doesn't help you to understand the command, please read man/info gawk.

Upvotes: 3

Related Questions