35

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?

4 Answers 4

73

You use the head command to do this, with the -n argument with the number of lines from each file, like this:

head -n3 *

or

head -n3 *.txt

This also works for a single file:

head -n3 filename.txt
5
  • 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
    Commented Mar 5, 2011 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
    Commented Mar 5, 2011 at 14:03
  • 1
    @luri: It did output the filenames for me as well. Commented Mar 5, 2011 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
    Commented Mar 5, 2011 at 21:56
  • but if i want only couple of bytes, not lines of file ? i got big json file head dod not help ( Commented Jul 1, 2022 at 12:36
14

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
4

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...

1

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>

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .