Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have a folder with quite a few files in it. I want to display the following:

filename_1
first line of file1
second line of file1
third line of file1
filename_2
first line of file2
second line of file2
third line of file2
filename_3
first line of file3
second line of file3
third line of file3

etc. How can I do that?

share|improve this question
add comment

4 Answers 4

up vote 17 down vote accepted

Maybe shorter version:

head -n3 *

or

head -n3 *.txt

etc

share|improve this answer
    
Just as a comment (I DO like the cleanness of the proposed solution), this command won't write out filenames, but just the first lines of the files –  luri Mar 5 '11 at 0:01
    
@luri - Really? In Ubuntu head version head (GNU coreutils) 8.5 it by default will. Or maybe you're using an alias head --quiet? –  arrange Mar 5 '11 at 14:03
    
@luri: It did output the filenames for me as well. –  David Oneill Mar 5 '11 at 19:09
    
Damn yes... it was aliased (--silent, actually, instead of --quiet) and I don't know why. Two answers in one for arrange ;) –  luri Mar 5 '11 at 21:56
add comment

head

You use head with the -n option.

head -n 10 FILE

This will print the first ten lines of a file.

Another useful variation would be -n -NUMBER.

head -n -10 FILE

This will print all but the last ten lines of a file.

To solve your problem and get your desired output you can do the following.

basename * && head -n NUMBER *

or

basename *.FILETYPE && head -n NUMBER *.FILETYPE

This will get you following output:

FILENAME
LINE ONE
LINE TWO
LINE THREE
share|improve this answer
add comment

This will do what you want, hopefuly:

find . -print -exec head {} -n 3 \;

-print will show the filename and the rest (from -exec) will show the first 3 lines of each file

Change the number according to your needs...

share|improve this answer
add comment

To add the filename to the head output use 'head -v'. So 'head -vn 3 *.html' gives me:

# head -vn 3 *.html
==> WebInfo.html <==
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

==> convert.html <==
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

==> misc.html <==
<html>
<head>
<title>WIP</title>
share|improve this answer
add comment

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.