Need help on pattern matching and printing the same

Hi,

I need to match for the pattern '.py' in my file and print the word which contains.

For example:

cat testfile

a b 3 4.py 5 6
a b.py c.py 4 5 6 7 8
1.py 2.py 3 4 5 6 

Expected output:

4.py
b.py c.py
1.py 2.py

TIA

Hello Sumanthsv,

Could you please try following and let me know if this helps you.

awk '{for(i=1;i<=NF;i++){if($i ~ /.py/){printf("%s ",$i)}};print ""}'   Input_file

Thanks,
R. Singh

1 Like

Thanks ..its working fine

---------- Post updated at 06:45 AM ---------- Previous update was at 06:41 AM ----------

Hi RavinderSingh13

If possible,Could you please explain this below part of code given by you.

{printf("%s ",$i)}};print ""}

Hello Sumanthsv,

Could you please go through following and let me know if this helps you.

awk '{
for(i=1;i<=NF;i++){                ##### Starting a for loop here which will start from variable i's value 1 to till number of field's value(NF).
if($i ~ /.py/){                    ##### Checking a condition here if any field's value is equal to .py, if yes then perform following action.
printf("%s ",$i)}                  ##### printing the value of that field which is having .py in it with space. NO new line.(so that all .py values on a single line I could print on a single line only)
};
print ""}                          ##### Printing NULL value, which means it will print a new line.
'  Input_file                      ##### mentioning the Input_file here.

Thanks,
R. Singh

1 Like