LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   awk command line: blank line record sep, new line field sep (http://www.linuxquestions.org/questions/programming-9/awk-command-line-blank-line-record-sep-new-line-field-sep-784148/)

robertmarkbram 01-22-2010 11:45 PM

awk command line: blank line record sep, new line field sep
 
Hi All,

I have been trying to understand from the online awk manuals how to phrase this command line, but would greatly appreciate some help please.

I have a file (temp.txt) with these contents (one field per line, blank line separates records):

Code:

1st record, 1st field cat
1st record, 2nd field dog
1st record, 3rd field duck
1st record, 4th field cow

2nd record, 1st field car
2nd record, 2nd field boat
2nd record, 3rd field plane
2nd record, 4th field train

3rd record, 1st field plate
3rd record, 2nd field cup
3rd record, 3rd field fork
3rd record, 4th field knife

I want to find the record with the value "knife" for e.g. and print out the first field. This is what I have come up with so far:

Code:

awk -F=/ "/knife/ {print \$2}" RS="" "temp.txt"
I understand I need to change the field separator to a newline and record separator to a blank line, but I am getting really confused about how.

Also, does awk support the notion of saying "search for the value in the first field" etc?

Thank you for any assistance!

ghostdog74 01-23-2010 12:18 AM

Code:

$ awk -vRS= -vFS="\n" '/knife/{print $2}' file
3rd record, 2nd field cup


robertmarkbram 01-23-2010 12:35 AM

Quote:

Originally Posted by ghostdog74 (Post 3837346)
Code:

$ awk -vRS= -vFS="\n" '/knife/{print $2}' file
3rd record, 2nd field cup


Nice, thank you so much - the only other thing I would like to achieve is to narrow the search down, either to say "search in field x" or at least to say "must match whole field" (^searchTerm$ .. ?).

Thank you again!

grail 01-25-2010 01:22 AM

Well ghostdog74 probably has a cleverer solution but M2C:

awk -vRS= -vFS="\n" -v output="$1.*field $2$" '$0 ~ output { print $1 }' $3

and to your script you pass field number ($1), item ($2) and filename ($3)

robertmarkbram 02-21-2010 05:25 AM

In a script:
Code:

awk -vRS= -vFS="\n" "{if (\\$5 == \"$1\") print \\$1}" temp.txt
$1 is "knife"..


All times are GMT -5. The time now is 08:59 AM.