[英]How to prepend filename to last lines of files found through find command in Unix
我有一個需要以格式顯示目錄下所有文件的最后幾行的要求
filename: lastline
我發現以下代碼
find /user/directory/* -name "*txt" -mtime 0 -type f -exec awk '{s=$0};END{print FILENAME, ": ",s}' {} \;
但是我讀到這會每次讀取整個文件。 我目錄中的文件很大,所以我負擔不起。 我有其他選擇嗎?
find /user/directory/* -name "*txt" -mtime 0 -type f | while IFS= read -r file
do
echo -n "$file: "
tail -1 "$file"
done
重要的變化是tail -1不會讀取整個文件,而是從末尾讀取一小部分,並增加它們直到找到完整的最后一行。
如果您知道目錄名稱:
for f in $(/bin/ls directory/*.txt); do
echo "$f: $(tail -1 $f)"
done
會成功的 更普遍,
for f in $(find /user/directory -type f -name "*.txt"); do
echo "$f: $(tail -1 $f)"
done
也會工作。 程序tail
將開始從頭開始讀取文件,而tail -n
將僅讀取指定文件的最后n
行。
在其他答案中使用tail
會很好。 現在,您可以將所有這些包裝到find
命令中。
如果find
支持-printf
命令:
find /user/directory/ -name "*txt" -mtime 0 -type f -printf '%p: ' -exec tail -1 {} \;
如果find
不支持-printf
命令:
find /user/directory/ -name "*txt" -mtime 0 -type f -exec printf '%s: ' {} \; -exec tail -1 {} \;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.