rcwizard12435
rcwizard12435

Reputation: 63

How can I use grep and awk commands on a text file while maintaining line order?

I have a text file that looks like this:

domain name pointer www.google.com
domain name pointer www.gmail.com
NA
domain name pointer www.facebook.com
NA
NA
NA
domain name pointer www.starbucks.com

IF I use these commands:

grep "pointer" inputfile.txt | awk '{print $4}'

grep "NA" inputfile.txt | awk '{print $1}'

I am able to get:

www.google.com
www.gmail.com
www.facebook.com
www.starbucks.com
NA
NA
NA
NA

However I would like the 'NA' and URLS to stay in the same order as the original text file.

Upvotes: 0

Views: 302

Answers (2)

Ed Morton
Ed Morton

Reputation: 204258

If one of these isn't all you need:

$ awk '{print $NF}' file
www.google.com
www.gmail.com
NA
www.facebook.com
NA
NA
NA
www.starbucks.com

$ sed 's/.* //' file
www.google.com
www.gmail.com
NA
www.facebook.com
NA
NA
NA
www.starbucks.com

then edit your question to clarify your requirements and provide more truly representative sample input/output.

Upvotes: 1

Barmar
Barmar

Reputation: 782107

There's no need to use grep, since awk can do pattern matching all by itself. Then you don't need to use multiple passes over the file:

awk '/pointer/ {print $4} 
     /NA/ {print $1}' inputfile.txt

Upvotes: 2

Related Questions