2

Suppose I have a file.txt with the following lines :

hello myname1 is yellow.pcapng red
festive myname33 is hddd.pcapng dfdf
crude myname44 is hello.pcapng

Now my goal is to filter to the lines so it outputs to out.txt as follows :

myname1 yellow.pcapng
myname33 hddd.pcapng
myname44 hello.pcapng

Now I know that I can use :

grep -oh "\w*myname\w*" /tmp/file.txt  > /tmp/out.txt
grep -o '[^ ]\+g' /tmp/file.txt > /tmp/out.txt 

to get the both respective parts of the expression individually. How do I combine these commands so that I get my desired output?

  • 3
    do you have to use grep? You have a problem that's begging for an awk solution, and awk should be available everywhere that grep is. – Jeff Schaller Jun 3 at 18:05
  • I was only familiar with grep and not awk, could you show me how to do using awk possibly? – gangsignwall Jun 3 at 18:13
  • @JeffSchaller It's actually begging for a cut solution, since this is exactly what cut is supposed to do – ChatterOne Jun 4 at 9:57
  • Good thing there is a cut solution, @ChatterOne! – Jeff Schaller Jun 4 at 10:30
5

Given your sample data, you could assume that words #2 and #4 are what you want to extract; you'd express that in awk with:

awk '{ print $2, $4 }' < /tmp/file.txt > /tmp/out.txt
3

You could use cut:

cut -d' ' -f2,4 < /tmp/file.txt > /tmp/out.txt 
2

Using awk instead of grep.

awk '{print $2,$4}' /tmp/file.txt > /tmp/out.txt

You are piping the output of cat file.txt to awk.

Then using awk expressions '{print $2,$4}', you are printing the 2nd and 4th field of the split line, with a space to separate.

Your output will be how you desire.

1

Could do this too:

cat file.txt | sed "s/.*\(myname[0-9]*\) is \([^ ]*\).*/\1 \2/g" | grep ^myname > /tmp/out.txt

0

Since shell script method has been provided above, Tried in Python and worked fine too

#!/usr/bin/python
o=[]
k=open('i','r')
for z in k:
    o.append(z.strip().split(' ')[1])
        o.append(z.strip().split(' ')[3])
for d in range(0,len(o),2):
    print " ".join(o[d:d+2])

output

myname1 yellow.pcapng
myname33 hddd.pcapng
myname44 hello.pcapng

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.