Masiar
Masiar

Reputation: 21352

Printing a line of a file given line number

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

Answers (7)

blackcoffeerider
blackcoffeerider

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

potong
potong

Reputation: 58558

This might work for you:

sed '10q;d' file

Upvotes: 0

mvp
mvp

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

Guru
Guru

Reputation: 17054

Using awk:

awk 'NR==10' file

Using sed:

sed '10!d' file

Upvotes: 9

Anders Lindahl
Anders Lindahl

Reputation: 42940

sed -n '10{p;q;}' example.c

will print the tenth line of example.c for you.

Upvotes: 7

Adam Sznajder
Adam Sznajder

Reputation: 9216

head -n 10 /tmp/asdf | tail -n 1

Upvotes: 2

Gregor
Gregor

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

Related Questions