Pattern matching using awk

Hi I am trying to find a pattern match with column one containing 3 numbers.

input file tmp.lst

abcd456|1|23123|123123|23423
kumadff|a|dadfadf|adfd|adfadfadf
xxxd999|d|adfdfs|adfadf|adfdasfadf
admin|a|dafdf|adfadfa|||

output file tmp4.lst

abcd456|1|23123|123123|23423
xxxd999|d|adfdfs|adfadf|adfdasfadf

My code is

echo `awk '{if ($1 ~ /^[a-z]*[0-9][0-9][0-9]/) print NR, $0, "\n"} "\n"' tmp.lst` > tmp4.lst

the problem is i am getting all the output in same line like

abcd456|1|23123|123123|23423xxxd999|d|adfdfs|adfadf|adfdasfadf

Pls tune this to get a correct output.

---------- Post updated at 01:26 PM ---------- Previous update was at 01:25 PM ----------

In command line i get in newline seperated but not when i write in file.

Please use the code tags as required per forum rules.

You were close with your awk script, try removing the last instance of new line ("\n"), so it becomes:

echo `awk '{if ($1 ~ /^[a-z]*[0-9][0-9][0-9]/) print NR, $0, "\n"}' tmp.lst` > tmp4.lst

For me this outputs:

1 abcd456|1|23123|123123|23423

3 xxxd999|d|adfdfs|adfadf|adfdasfadf


Or, you could simply use:

awk -F"|" '$1~/[0-9][0-9][0-9]/' tmp.lst` > tmp4.lst

Why echo ` ` ?

awk '{if ($1 ~ /^[a-z]*[0-9][0-9][0-9]/) print NR, $0}' tmp.lst > tmp4.lst

Posted by vamsekumar:

Hello vamsekumar,

According to your condition the first field which has 3 digits following may also help.

awk  '($1 ~ /[0-9][0-9][0-9]/) {print NR OFS $0}' Input_file > Output_file

Thanks,
R. Singh


  1. a-z ↩︎