Click here for important information about

Solved print only the string from all line

January 29, 2015 at 09:35:02
Specs: Windows Vista

Purpose, “print only the string from all line”

My example-file is:

Row, 1, first, a, a, a, a, a, NUMBER-100111, and, WORD-something, a, a
Row, 2, And, second, number, could, be, NUMBER-100222, and, WORD-something_else, b,
Row, 3, Last , line, a, a, a, a, a, a, a, NUMBER-100322, b ,b ,b ,b ,b ,b, WORD-hello

“command should be:”
grep “NUMBER-xxxxxx” and “WORD-xxxxxxx” and print just NUMBER and WORD” > new_file

And new_file should be as below.

NUMBER-100111, WORD-something
NUMBER-100222, WORD-something_else
NUMBER-100322, WORD-hello

Is this possible?



message edited by johan

See More: print only the string from all line

January 29, 2015 at 15:45:21
✔ Best Answer
It's possible, but not with just grep as grep returns the entire line if the NUMBER or WORD pattern exist. How about an awk script that cycles thru each field (Field Seperator is a comma) and captures the field if it starts with NUMBER of WORD:


# look at each field in the line.  Assume if each line has a NUMBER,
# it has a WORD
# using nawk because I'm using Solaris
nawk ' FS="," {
   gsub(" ","") # get rid of all spaces
   for (i=1; i<=NF; i++)
      if( $i ~ /^NUMBER/)
      if($i ~ /^WORD/)
   printf("%s,%s\n", f1, f2)
} ' examfile.txt

message edited by nails

Report •

January 29, 2015 at 18:18:04
Thank you for your prompt reply. Your rule works well.


Report •
Related Solutions

Ask Question