我可以创建什么命令来列出给定目录中所有文件的前 4 行?
答案1
[root@xxx httpd]# head -n 4 /var/log/httpd/*
==> /var/log/httpd/access_log <==
xxxx - - [06/Dec/2015:22:22:45 +0100] "GET / HTTP/1.1" 200 7 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36 Vivaldi/1.0.303.52"
xxxx - - [06/Dec/2015:22:22:46 +0100] "GET /favicon.ico HTTP/1.1" 404 291 "http://195.154.165.63:8001/" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.99 Safari/537.36 Vivaldi/1.0.303.52"
==> /var/log/httpd/access_log-20151018 <==
xxxx - - [12/Oct/2015:14:05:42 +0200] "GET /git HTTP/1.1" 404 281 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0"
xxxx - - [12/Oct/2015:14:05:42 +0200] "GET /favicon.ico HTTP/1.1" 404 289 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0"
xxxx - - [12/Oct/2015:14:05:43 +0200] "GET /favicon.ico HTTP/1.1" 404 289 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0"
xxxx - - [12/Oct/2015:14:06:24 +0200] "GET /git HTTP/1.1" 502 465 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0"
==> /var/log/httpd/access_log-20151115 <==
xxxx - - [14/Nov/2015:18:56:04 +0100] "GET / HTTP/1.1" 200 7 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0"
xxxx - - [14/Nov/2015:18:56:05 +0100] "GET /favicon.ico HTTP/1.1" 404 291 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0"
xxxx - - [14/Nov/2015:18:56:05 +0100] "GET /favicon.ico HTTP/1.1" 404 291 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0"
xxxx - - [14/Nov/2015:18:58:28 +0100] "GET /phpmyadmin HTTP/1.1" 403 294 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0"
这是我的 httpd 目录的示例,其中head -n 4 /var/log/httpd/*
包含前 4 行命令。将第一行替换head -n 4
为。head -n 1
/var/log/httpd/*
例如,您可以将目录替换为您的目录,/my/directory/*
但不要忘记末尾的通配符 ( *
)。该通配符允许告诉我们我们想要目录中的所有(非隐藏)文件。
答案2
如果您只想要这 4 行内容而不是文件名:
awk 'FNR<=4' ./*.log
要将文件名作为行前缀:
awk 'FNR<=4 {print FILENAME ": " $0}' ./*.log
或者使用 GNU grep
:
grep -Hm4 '^' ./*.log
答案3
如果“所有文件”指的是“常规文件”而不是目录、套接字、FIFO 等,那么您需要使用以下命令来查找这些文件find
:
find "$dir" -maxdepth 1 -type f
并将它们传递给xargs
调用head
它们:
find "$dir" -maxdepth 1 -type f -print0 | xargs -0 head -n 4
如果您还想跟踪最终指向常规文件的符号链接,请使用-xtype
in 代替-type
(或使用find -L
代替find
)。
(我假设是 GNUfind
及xargs
以上版本;如果您不在 GNU 环境中,请参阅注释中的注释)。