3

I have a wordlist that I'd like to extract every line of text from that contains only numbers, to a new file. What do I do?

5

To extract only lines containing digits:

$ grep '^[0-9][0-9]*$' words >digits

The regular expression ^[0-9][0-9]*$ will match any line which begins with a digit and then contains only digits until the end of line.

If your file doesn't have empty lines, you may change it to ^[0-9]*$.

If you want lines with numbers, delete lines with alphabetic characters instead (easier than trying to construct a regular expression for a generic number):

$ grep -v '[a-zA-Z]' words >numbers

Both variants using POSIX character classes:

$ grep '^[[:digit:]][[:digit:]]*$' words >digits
$ grep -v '[[:alpha:]]' words >numbers

Update: If you want to select the lines containing floating point numbers you could use the (extended) regular expression ^[+-]?([0-9]*\.)?[0-9]+$:

$ grep -E '^[+-]?([0-9]*\.)?[0-9]+$' words >floats

It all comes down to what kind of "number" we're looking for.

  • could use ^[0-9]\+$ instead of ^[0-9][0-9]*$ – Sundeep Aug 13 '16 at 9:29
  • 2
    @spasic Yes, and it would be more efficient on large data sets. I kept to only using * though as it doesn't need changing in any way when one switches between BREs and EREs. – Kusalananda Aug 13 '16 at 9:43
4

Delete any line containing letters by sed and then put your output to another file:

sed '/[a-z]/Id' yourInputFile > yourOutputFile

OR if you want to change the original file in-place:

sed -i '/[a-z]/Id' yourInputFile 
  • I think there is a typo - should be /[a-z]/d;/[A-Z]/d but better to use one regex instead of two.. /[a-zA-Z]/d – Sundeep Aug 13 '16 at 9:27
  • or /[a-z]/Id to do a case-insensitive match – Sundeep Aug 13 '16 at 9:32
  • @spasic Oh my bad, yes it was typo. Thanks for mentioning. And yes /[a-z]/Id is better. I will update my answer. Thanks. – Parsa Samet Aug 13 '16 at 9:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.