[英]using sed to search for first 3 and last 3 occurrences of all the files
在目录的所有文件中搜索字符串的前 3 次和后 3 次出现以及 output 结果到文件的最佳方法是什么?
我目前正在使用 2 个命令执行此操作。 但是有更好的方法吗?
grep string path-to-file | head -3 > out.log
grep string path-to-file | tail -3 >> out.log
这可以在单个 awk 调用中完成,例如:
awk -v n=3 '
FNR == 1 && NR != 1 {
i = ((c - n) >= n ? c - n : n) + 1
for (; i <= c; i++)
print m[i]
c = 0
delete m
}
/pattern to match/ {
c++
if (c <= n)
print
else {
delete m[c - n]
m[c] = $0
}
}
END {
i = ((c - n) >= n ? c - n : n) + 1
for (; i <= c; i++)
print m[i]
}' *
如果您仍然感兴趣:
see -n '
/PATTERN/!{$be;d};
1h;1!H;
:e;
${g;s,^\([\n]\+\n[\n]\+\n[\n]\+\n\).*\([\n]\+\n[\n]\+\n[\n]\+\),\1\2,;p}
'
这个想法是:
我现在无法访问计算机,稍后我会检查并在必要时修复它
这可能对您有用(GNU sed):
sed -nE '/PATTERN/H;$!d;x;s/^((\n[^\n]*){3}).*((\n[^\n]*){3})$/\1\3/;s/.//p' file
在保持空间和文件末尾收集包含PATTERN
的行,交换到保持空间,删除前三行和最后三行之间的任何行,删除引入的换行符,如果成功则打印。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.