bash - 给定一个 logfile.txt,我只想提取 java 脚本名称;例如使用 bash 脚本的 filename.js

标签 bash awk cut text-manipulation

我使用以下 awk 脚本来执行此操作,

for line in $1
do
 grep -F ".js" $1 | awk '{print $7}' | sort -u 
done 

输出即将完成:

/blog/wp-includes/js/swfobject.js?ver=2.2
/fla/AC_RunActiveContent.js
/include/jquery.js
/include/jquery.jshowoff2.js
/include/jquery.jshowoff.min.js
/include/js/jquery.lightbox-0.5.js
/scripts/ac_runactivecontent.js

我尝试使用管道: cut -d "/"-f5 代替 awk,但部分脚本名称也被切断。

ac_runactivecontent.js HTTP
AC_RunActiveContent.js HTTP
jquery.jshowoff2.js HTTP
jquery.jshowoff.min.js HTTP
jquery.js HTTP
js
wp-includes

我如何从模式 .js 中提取到分隔符“/”,以便我只获得脚本文件名:

swfobject.js
AC_RunActiveContent.js
jquery.js
jquery.jshowoff2.js
jquery.jshowoff.min.js
jquery.lightbox-0.5.js
ac_runactivecontent.js

最佳答案

用单个 awk (和可选的 sort)替换当前的 for/grep/awk/sort 可能会更有效>).

设置:

$ cat filename.js
1 2 3 4 5 6 /blog/wp-includes/js/swfobject.js?ver=2.2 8 9 10
ignore this line
1 2 3 4 5 6 /fla/AC_RunActiveContent.js 8 9 10
1 2 3 4 5 6 /include/jquery.js 8 9 10
ignore this line
1 2 3 4 5 6 /include/jquery.jshowoff2.js 8 9 10
1 2 3 4 5 6 /include/jquery.jshowoff.min.js 8 9 10
ignore this line
1 2 3 4 5 6 /include/js/jquery.lightbox-0.5.js 8 9 10
1 2 3 4 5 6 /scripts/ac_runactivecontent.js 8 9 10

一个awk想法:

awk '
/.js/ { n=split($7,a,"[/?]")          # split field #7 on dual characters "/" and "?", putting substrings into array a[]
        for (i=n;i>=1;i--)            # assuming desired string is toward end of $7 we will work backward through the array
        if (a[i] ~ ".js") {           # if we find a match then ...
           print a[i]                 # print it and break out of the loop ...
           next                       # by going to next input record
        }
      }
' filename.js

# or as a single line:

awk '/.js/ {n=split($7,a,"[/?]"); for (i=n;i>=1;i--) if (a[i] ~ ".js") { print a[i]; next}}' filename.js

这会生成:

swfobject.js
AC_RunActiveContent.js
jquery.js
jquery.jshowoff2.js
jquery.jshowoff.min.js
jquery.lightbox-0.5.js
ac_runactivecontent.js

注意:如果需要,OP 可以通过管道将结果进行排序

关于bash - 给定一个 logfile.txt,我只想提取 java 脚本名称;例如使用 bash 脚本的 filename.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73295911/

相关文章:

bash - 关闭命名文件描述符

bash - 从 bash 打开然后杀死子进程

使用awk将一个文件中的列替换为另一个文件中的列?

linux - 如何使用 bash 命令从字符串中提取子字符串

用于从文本中剪切列的 Windows 命令

linux - Bash 终端 - .profile 不调用终端中的某些函数

bash - 如何忽略/恢复文件内容中大小写的更改?

java - Ubuntu 中的 Bash 脚本错误 : awk: line 1: regular expression exceeds implementation size limit

bash - 如何根据 awk 中的多个范围计算行数?

python - 在 Pandas 中创建一个带有标签的列来对 DataFrame 进行分区。