bash尾部文件夹中的最新文件不包含变量 [英] bash tail the newest file in folder without variable

查看:50
本文介绍了bash尾部文件夹中的最新文件不包含变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文件夹中有一堆日志文件.当我进入该文件夹并查看文件时,它看起来像这样.

I have a bunch of log files in a folder. When I cd into the folder and look at the files it looks something like this.

$ ls -lhat
-rw-r--r--   1 root root 5.3K Sep 10 12:22 some_log_c48b72e8.log
-rw-r--r--   1 root root 5.1M Sep 10 02:51 some_log_cebb6a28.log
-rw-r--r--   1 root root 1.1K Aug 25 14:21 some_log_edc96130.log
-rw-r--r--   1 root root 406K Aug 25 14:18 some_log_595c9c50.log
-rw-r--r--   1 root root  65K Aug 24 16:00 some_log_36d179b3.log
-rw-r--r--   1 root root  87K Aug 24 13:48 some_log_b29eb255.log
-rw-r--r--   1 root root  13M Aug 22 11:55 some_log_eae54d84.log
-rw-r--r--   1 root root 1.8M Aug 12 12:21 some_log_1aef4137.log

我想查看最新日志文件中的最新消息.现在,我可以手动复制最新日志的名称,然后在其上执行尾巴,这将起作用.

I want to look at the most recent messages in the most recent log file. I can now manually copy the name of the most recent log and then perform a tail on it and that will work.

$ tail -n 100 some_log_c48b72e8.log 

这确实涉及体力劳动,所以我想使用bash-fu来做到这一点.

This does involve manual labor so instead I would like to use bash-fu to do this.

我目前发现可以这样做;

I currently found this way to do it;

filename="$(ls -lat | sed -n 2p |  tail -c 30)"; tail -n 100 $filename

它可以工作,但是让我感到沮丧的是,我需要将数据保存到变量中才能执行此操作.是否可以在bash中执行此操作而无需将中间结果保存到变量中?

It works, but I am bummed out that I need to save data into a variable to do it. Is it possible to do this in bash without saving intermediate results into a variable?

推荐答案

tail -n 100 "$(ls -at | head -n 1)"

您不需要 ls 来真正打印时间戳,只需要按它们排序( ls -t ).我添加了 -a 选项,因为它位于您的原始代码中,但是请注意,除非您的日志文件是点文件"(即以开头.),否则这不是必需的.(他们不应该).

You do not need ls to actually print timestamps, you just need to sort by them (ls -t). I added the -a option because it was in your original code, but note that this is not necessary unless your logfiles are "dot files", i.e. starting with a . (which they shouldn't).

以这种方式使用 ls 可以避免使用 sed tail -c 解析输出.(并且您应该尝试解析 ls .)只需选择列表中的第一个文件( head -n 1 ),这是最新的文件.将其放在引号中可以使您避免使用更常见的问题",例如文件名中的空格.(如果文件名中包含换行符或类似内容,请修复文件名.:-D)

Using ls this way saves you from parsing the output with sed and tail -c. (And you should not try to parse the output of ls.) Just pick the first file in the list (head -n 1), which is the newest. Putting it in quotation marks should save you from the more common "problems" like spaces in the filename. (If you have newlines or similar in your filenames, fix your filenames. :-D )

您可以就地使用命令替换,而不是保存到变量中.

Instead of saving into a variable, you can use command substitution in-place.

这篇关于bash尾部文件夹中的最新文件不包含变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆