Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I would like to be able from the command line to search for a name and it say the letter A,B,C,D,E,F it appears under, and the name, and not stuff in between. So if I search for tim it should say:

B  
tim

Here is the file:

A
bob

john

B
tom

tim

C
phil 
bob

D
gary
tony

E
anne
rachel

F
gareth
share|improve this question

2 Answers 2

up vote 1 down vote accepted

Okay, how about something more like this:

awk "/^[A-Z]\$/{ l=\$1 ; } ; /^${NAME}\$/ { print l ; exit ; };"

Cons: Involves quoting (which I personally try to avoid) and regexes (which are hard to understand) and awk (which is hard to understand)

Pros: I think this does the trick, at least as I understand it revisedly.

(it may not go without saying that you should replace ${NAME} with the entry that you're searching for, e.g. tim)


The explanation that was requested in the comments section:

/^[A-Z]\$/{ l=\$1 ; }

For each line that is a single capital letter, assign the first (only) item on that line to the variable l (letter ell).

/^${NAME}\$/ { print l ; exit ; }

For each line that matches ${NAME} (you should substitute the thing you're looking for for ${NAME}, as I said above, or set and export the NAME environment variable before running the command), print the most recent value for the variable l, and then exit. Effectively, the program exits as soon as it encounters a line that is exactly the value specified, right after printing the most recently encountered line matching the first regular expression.

I quoted all of the $'s other than the one used for ${NAME} because I used double-quotes instead of single-quotes (to permit ${NAME} to expand, but to avoid messing with the other $'s.

share|improve this answer
    
I am familiar with regex but not awk. Can you explain the awk parts including the reason for the quotes? And Where does file get mentioned? –  barlop Jul 7 '11 at 16:46
grep -B1 <searchstring> <filename>

E.g.

grep -B1 tim file
share|improve this answer
    
no, see my question, for what I want to display and what I don't want to display –  barlop Jul 7 '11 at 1:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.