sed - print only matching regex

Hi folks,

Lets say I have the following text file:

name, lastname, 1234, name.lastname@test.com
name1, lastname1, name2.lastname2@test.com, 2345
name, 3456, lastname, name3.lastname3@test.com
4567, name, lastname, name4.lastname4@test.com

I now need the following output:

1234
2345
3456
4567

Is 'sed' the right way? If yes: How can I print out just the matching regex?

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

awk?

 awk -F', '   '{ for(i=1; i<=NF; i++) if($i ~/[0-9]{4}/) {print $i} }' filename

Or maybe perl ? :wink:

perl -ne '{chomp; @x=split/, /; foreach $item (@x){$item =~ /\d{4}/ && print $item,"\n"}}' input.txt

tyler_durden

# perl -ne 'print  if s/.*(\d{4}).*/\1/' file
1234
2345
3456
4567

OMG. Thanks so much guys.

But unfortunately I prefere awk :wink:

@ jim mcnamara:

How can I just print out four (4) characters.

If the field is four numbers, and you have -F', ' (with a modern awk) leading and trailing delimiters will be removed. In this case I set delimiters as space and comma. You may need to add other whitepsace characters like tab to the -F option argument. I don't know what is in your file.

Try

awk -F', '   '{ for(i=1; i<=NF; i++) if($i ~/[0-9]{4}/) {print $i} }' filename | od -c | more

to see what kinds of extra characters you are getting. -F '[^0-9]' makes everything that is not a number a field delimiter, if you cannot tell what to exclude