From below lines

abcd efgh ijhk lmn opqrs tuv wxyz
abcd efgh ijhk lmn opqrs 

How to extract only
  • It would be more helpful if your sample had more examples of things you don't want it to match (like what about foo1.2, foo-1.2, 1.2-3). How do you define word? How do you define number? 9c being a number implies numbers here are hexadecimal numbers. Is that right? – Stéphane Chazelas Dec 6 '18 at 9:10
  • Why isn't abcd to be matched? That's an hexadecimal number as well. Is that because you need those words to contain at least two numbers? – Stéphane Chazelas Dec 6 '18 at 9:44

Try this,

 grep -E -o '[0-9]\.[0-9]\.[0-9]\.[0-9][^[:space:]]+' file
  • -E Interpret PATTERN as an extended regular expression
  • -o Print only the matched parts of a matching line
  • [^[:space:]]+ until white space
  • @StéphaneChazelas Thanks, updated for dot, ... – msp9011 Dec 6 '18 at 9:11
  • @StéphaneChazelas i ment \w+ as untile white space, since \w followed by +.... correct me if im wrong... – msp9011 Dec 6 '18 at 9:13

If by word, you mean sequence of non-whitespace characters, and by number, you mean hexadecimal (without sign or leading 0x, so sequence of 0123456789abcdefABCDEF characters), and that you need at least two of those numbers per word (otherwise abcd would be matched as well), with GNU grep you can do:

grep -Pio '(?<!\S)[0-9a-f]+(\.[0-9a-f]+)+(?!\S)'

Or with perl:

perl -lne 'for (/\S+/g) {print if /^[\da-f]+(\.[\da-f]+)+$/}'

Assuming the values are inside a file, with pcre grep:

 $ grep -P '(([0-9a-f]+)\.)(?1)+(?2)' file

Or with perl:

 perl -lne '/((([\da-f]+)\.)(?2)+(?3))/;print $1' file

Try also

grep -oE "(\w*[.]\w*)*" file
  • Perhaps end with + instead of *, to avoid matching the empty string? The output will be the same, but the * form will report "success" even on files containing no such words. – JigglyNaga Dec 6 '18 at 13:48

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.