采取最新的日志文件&存储在变量中

时间:2014-11-04 18:45:43

标签: linux bash shell datetime grep

我正在寻找一个grep最新日志文件的解决方案(例如abc-20141028-005356.log),该文件已被修改。我可以使用命令“ls -1t | head -1”执行此操作,它提供了解决方案,但是还有其他文件也会在日志文件夹中进行修改。我尝试使用头-2来提供2个文件&然后grepped文件...说“ls -1t | head -2 | grep abc - ”。

真正的问题是,当我们使用相同的文件名时,最新数据和新时间&日期。如何将最新的日志文件存储到具有相同重复文件名和变量的变量中?拖尾与日期&时间。

PATH=`cd $1 ; ls -1t | head -1`
LOGFILE=$1$PATH

$ 1 = /选择/ server1的/日志/

请告知相同的

我无法根据时间戳grep一个唯一的文件,因为实例abc-20141028-005356.log被修改了&下一个文件是abc-20141028-005358.log,这只是时间差异..但完整的文件名保持不变。

需要一个解决方案,我可以将修改后的最新文件分配给变量,而不管文件名和文件名是什么。时间戳(最新修改)

I have couple of files here

total 0
-rw-r--r-- 1 root root 0 Nov  4 11:14 abc-20141028-005348.log
-rw-r--r-- 1 root root 0 Nov  4 11:14 abc-20141028-005358.log
-rw-r--r-- 1 root root 0 Nov  4 11:19 abc-20141029-005358.log
-rw-r--r-- 1 root root 0 Nov  4 11:19 abc-20141029-005360.log

This is the latest file i get if i use the below

[root@abcd RKP]# ls -1t | head -1
abc-20141029-005360.log

The above can be done when there is only files starting with abcd-***. Now i have the below files

-rw-r--r-- 1 root root 0 Nov  4 11:14 abc-20141028-005348.log
-rw-r--r-- 1 root root 0 Nov  4 11:14 abc-20141028-005358.log
-rw-r--r-- 1 root root 0 Nov  4 11:19 abc-20141029-005358.log
-rw-r--r-- 1 root root 0 Nov  4 11:19 abc-20141029-005360.log
-rw-r--r-- 1 root root 0 Nov  4 11:21 EFG-20141028-005348.log
-rw-r--r-- 1 root root 0 Nov  4 11:21 EFG-20141028-005358.log
-rw-r--r-- 1 root root 0 Nov  4 11:21 EFG-20141029-005358.log

When i do the above command 

[root@abcd RKP]# ls -1t | head -1
EFG-20141029-005358.log

I want only files which are modified on abcd-XXXXX.XXXX based on the last modfied time.

I'm sorry for making this so confused. Please let me know if you need anything more.

The solution may be simple, but I'm not getting how to do this. !!!!

谢谢你的工作......

谢谢......这很有效。在我的脚本中运行上面的内容时,我得到这个错误行30:[::整数表达式预期

知道我错过了什么。同一部分的脚本如下。

 if [ -e $POSFile ]; then
# Read last Position
lastPosition=`cat $POSFile`
fi
fileLength=`stat -c %s $LOGFILE`

if [ "$lastPosition" -gt "$fileLength" ]; then
# Log file rolled
lastPosition=0;
fi

difference=`expr $fileLength - $lastPosition`
# New Spot  To POSFile

    enter code here

echo $fileLength > $POSFile      

1 个答案:

答案 0 :(得分:1)

要在某个目录abc-中获取以$1开头的最新文件:

ls -t "$1"/abc-* | head -n1

如果没有文件与此模式匹配,则会出现No such file or directory错误。在这种情况下,请检查$1的值。一些有用的命令:

echo $1
ls "$1"
ls "$1"/abc-*

帖子中的小脚本代码段应为:

LOGFILE=$(ls -t "$1"/abc-* | head -n1)

我还注意到您正在尝试将PATH=设置为某些内容。这可能不会很好。 shell中的PATH变量是特殊的,它包含shell查找可执行文件的路径列表。为变量使用不同的名称,例如path=将是正常的(全部小写)。

至于问题的第二部分:

  

第30行:[::预期的整数表达式

这必须来自这一行:

if [ "$lastPosition" -gt "$fileLength" ]; then

-gt的两边必须是整数才能使其生效。添加一些echo行以检查这些变量是否真的是数字,例如:

echo lastPosition=$lastPosition
echo fileLength=$fileLength
if [ "$lastPosition" -gt "$fileLength" ]; then

此外,最好使用`...`重写所有$(...)