I got a question during one of my interviews intended to determine my level of knowledge of Linux command-line and command-line tools.
Given a file called file with 16 names each on its own line, print out only the middle eight names.
The simplest answer, of course is:
head -12 file | tail -8However, we had just been discussing my thesis—for which I had done a lot of bash scripting—and instead of thinking of that first, my answer came out:
count=0; for line in `cat file`; do let count=count+1; if [[ "$count" -gt "4" ]]; then if [[ "$count" -le "12" ]]; then echo $line; fi; fi; done“Nobody I recall has whipped out bash scripting quite so readily for this. Can you think of another way?” asked the interviewer.
Only then did I think of using head and tail. I either impressed or confused him. Possibly both. I did get the job, though.
I’m glad you got the job, but you didn’t get the simplest answer :-)
Given this file ‘file’ with 16 names:
% cat file
1 Andrew
2 Brian
3 Chris
4 Dave
5 Ethan
6 Frank
7 Greg
8 Hannah
9 Isaac
10 Joseph
11 Kelly
12 Lauren
13 Mike
14 Nathan
15 Orville
16 Peter
You can get the middle 8 with one sed command and no fork:
% sed -n '5,12p' file
5 Ethan
6 Frank
7 Greg
8 Hannah
9 Isaac
10 Joseph
11 Kelly
12 Lauren
This has been a nerd-off.
| Previous Post | Home | Next Post |
I’m glad you got the job, but you didn’t get the simplest answer :-) Given this file ‘file’ with 16 names: % cat file 1...