Extracting entries starting with xxx

Hello,
I am trying to extract all words (entries) from a file beginning with 123. For example:

ververv ewfaafa 123asd 4334j fdgfgf
fdfdssd 123890 xxxxx eeee sss 1234 sdfsf were sfs fbdsdfb
fsdg sdgfsd bfg sdfb dsfb 
sdfg sdf ergerg 123pop sdfgdfg 123ww 123qq dffg

Desired output:

123asd
123890
1234
123pop
123ww
123qq

Thanks so much!

awk '{ for(i=1;i<=NF;i++) if($i ~ /^123/) print $i; }' file
1 Like

Just to provide an alternative, assuming that your words are space-separated:

tr ' ' '\n' < yourfile | grep ^123

Or if you have GNU grep :

grep -o '123[a-zA-Z0-9]*' file

EDIT: My bad, please ignore this post. Thanks Scrutinizer for pointing that out.

The latter command would also print when 123 is not the start of a word, for example:

$ echo 4123x | grep -o '123[a-zA-Z0-9]*'
123x
1 Like