我有一个文件,我正在该文件上运行 tail 命令,如下所示
tail -n+1 -F "./log/catalina.log"
我想为该文件中的每一行添加后缀或前缀另一个字符串,该字符串可以是文件名本身,这样如果文件内容如下所示:
INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version: Apache Tomcat/9.0.1
INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built: Sep 27 2017 17:31:52 UTC
INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server number: 9.0.1.0
INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name: Linux
输出应如下所示:
Cataline.log INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version: Apache Tomcat/9.0.1
Cataline.log INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built: Sep 27 2017 17:31:52 UTC
Cataline.log INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server number: 9.0.1.0
Cataline.log INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name: Linux
答案1
如果你想检测管道另一端的文件名,你可以使用,-v
选项tail
来始终打印标题,如下所示:
$ tail -v file
==> file <==
test1
test2
你可以捕获第一行并为其添加前缀:
$ tail -vf file | awk 'NR==1{f=$2;next} {print f,$0}'
file test1
file test2
对于上面的命令,文件名不应包含空格。涵盖这种情况的更好版本可能是:
tail -vf file | awk 'NR==1{f=substr($0,5,length-8);next} {print f,$0}'
或者使用自定义前缀:
tail -vf file | awk 'BEGIN{p="custom prefix"} {print p,$0}'
与自定义后缀类似:
tail -vf file | awk 'BEGIN{s="custom suffix"} {print $0,s}'
答案2
您可以使用awk
:
tail -f "./log/catalina.log" | awk '{print "Cataline.log",$0}'
或者sed
:
tail -f "./log/catalina.log" | sed 's/^/Cataline.log /'
答案3
和xargs
:
$ file="./log/catalina.log"
$ tail -n+1 -F "$file" | xargs -I {} echo "$(basename $file) {}"
catalina.log INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server version: Apache Tomcat/9.0.1
catalina.log INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server built: Sep 27 2017 17:31:52 UTC
catalina.log INFO [main] org.apache.catalina.startup.VersionLoggerListener.log Server number: 9.0.1.0
catalina.log INFO [main] org.apache.catalina.startup.VersionLoggerListener.log OS Name: Linux