显示文件的前几行


24

我有一个包含很多文件的文件夹。我要显示以下内容:

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

等等。我该怎么做?

Answers:


54

您可以使用head命令来执行此操作,并使用-n参数以及每个文件的行数,如下所示:

head -n3 *

要么

head -n3 *.txt

这也适用于单个文件:

head -n3 filename.txt

正如评论(我确实喜欢所建议解决方案的
简洁性

@luri-真的吗?在Ubuntu head版本中head (GNU coreutils) 8.5,默认情况下会。或者,也许您正在使用别名head --quiet
安排

@luri:它也为我输出了文件名。
David Oneill

该死的...它是别名(实际上是-静音,而不是-quiet),我不知道为什么。两个答案合为一体;)
luri 2011年

12

head-n选项一起使用。

head -n 10 FILE

这将打印文件的前十行。

另一个有用的变化是-n -NUMBER

head -n -10 FILE

这将打印文件的最后十行以外的所有内容。

要解决您的问题并获得所需的输出,可以执行以下操作。

basename * && head -n NUMBER *

要么

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

这将为您提供以下输出:

FILENAME
LINE ONE
LINE TWO
LINE THREE

4

希望如此,这将做您想要的事情:

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

-print将显示文件名,其余(来自- exec)将显示每个文件的前3行

根据您的需要更改号码...


1

要将文件名添加到head输出中,请使用'head -v'。所以'head -vn 3 * .html'给我:

# 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>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.