Reputation: 21352
Is it possible, in UNIX, to print a particular line of a file? For example I would like to print line 10 of file example.c
. I tried with cat
, ls
, awk
but apparently either these don't have the feature or I'm not able to properly read the man
:-).
Upvotes: 4
Views: 2053
Reputation: 52
Try this:
cat -n <yourfile> | grep ^[[:space:]]*<NUMBER>[[:space:]].*$
cat -n numbers the file
the regex of grep searches the line numbered ;-) The original mismatched as mentioned in the comments. Te current one looks for the exact match. - i.e. in the particular cas we need a line starting with an arbitrary amount () of spaces the followed by a space followed by whatever (.)
In case anyone thumbles over this regex and doesn't get it at all - here is a good tutorial to get you started: http://regex.learncodethehardway.org/book/ (it uses python regex as an example tough).
Upvotes: 1
Reputation: 116417
Unfortunately, all other solutions which use head
/tail
will NOT work incorrectly if line number provided is larger than total number of lines in our file.
This will print line number N or nothing if N is beyond total number of lines:
grep "" file | grep "^20:"
If you want to cut line number from output, pipe it through sed
:
grep "" file | grep "^20:" | sed 's/^20://'
Upvotes: 2
Reputation: 42940
sed -n '10{p;q;}' example.c
will print the tenth line of example.c
for you.
Upvotes: 7
Reputation: 4434
Try head and tail, you can specify the amount of lines and where to start.
To get the third line:
head -n 3 yourfile.c | tail -n 1
Upvotes: 5