Print file line with line number

Is it possible on UNIX to print a specific line of a file? For example, I would like to print line 10 of the example.c file. I tried with cat , ls , awk , but apparently either they don’t have this function, or I can’t read man correctly :-).

+4
source share
7 answers

Using awk:

 awk 'NR==10' file 

Using sed:

 sed '10!d' file 
+8
source
 sed -n '10{p;q;}' example.c 

will print the tenth line example.c for you.

+7
source

Try head and tail, you can specify the number of lines and where to start.

To get the third line:

 head -n 3 yourfile.c | tail -n 1 
+4
source

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

+2
source

Unfortunately, all other solutions that use head / tail will NOT work correctly if the line number is greater than the total number of lines in our file.

This will print the line number N or nothing if N exceeds the total number of lines:

 grep "" file | grep "^20:" 

If you want to cut the line number from the output, pass it through sed :

 grep "" file | grep "^20:" | sed 's/^20://' 
+2
source

Try the following:

 cat -n <yourfile> | grep ^[[:space:]]*<NUMBER>[[:space:]].*$ 

cat -n file numbers

grep regular expression searches for line with number ;-) The original does not match the comments. The current current search matches an exact match. - that is, in the specific case, we need a line starting with an arbitrary sum () of spaces, followed by a space, followed by any (.)

In case someone goes over this regular expression and doesn't get it at all - here is a good tutorial to get you started: http://regex.learncodethehardway.org/book/ (python regex syntax is used as an example).

+1
source

This might work for you:

 sed '10q;d' file 
0
source

All Articles