这完全可以通过 Awk 脚本实现...
#!/usr/bin/awk -f
BEGIN {
for (i = 1; i < ARGC; i++) {
if (ARGV[i] ~ "^--from=") {
_from = substr(ARGV[i], 8)
delete ARGV[i]
}
}
if (!_from) {
print "No '--from' argument provided!" > "/dev/stderr"
}
}
{
if (_flag) {
print $0
} else if ($0 ~ _from) {
_flag = 1
print $0
}
}
注意;上面的脚本是从from-till.awk 改编(精简)而来的,它将在--from 和--till 搜索表达式之间打印,因此可能需要针对这个特定的用例调整添加的命令行选项和变量名。
...允许使用文件作为输入...
head-trimmer.awk --from="^Owner" file-path.txt
...或重定向,例如EOF 或管道...
head-trimmer.awk --from="^Owner" <<'EOF'
find: Filesystem loop detected; `/nfs/.snapshot/nightly.4' has the same device number and inode as a directory which is 2 levels higher in the filesystem hierarchy.
find: Filesystem loop detected; `/nfs/.snapshot/nightly.5' has the same device number and inode as a directory which is 2 levels higher in the filesystem hierarchy.
find: Filesystem loop detected; `/nfs/.snapshot/nightly.6' has the same device number and inode as a directory which is 2 levels higher in the filesystem hierarchy.
Owner RepoName CreatedDate
val abc Fri Mar 16 17:01:07 PDT
p1 repo_pc Wed Mar 21 11:34:42 PDT
New fm Mon Mar 19 00:15:51 PD
EOF
... 并且 应该 将事物解析为...
Owner RepoName CreatedDate
val abc Fri Mar 16 17:01:07 PDT
p1 repo_pc Wed Mar 21 11:34:42 PDT
New fm Mon Mar 19 00:15:51 PD
... Awk 脚本可以更轻松地扩展和/或适应其他用例,正确使用它意味着可以消除对其他程序的不必要调用。
应该可以通过更多提示从管道中消除sed 和column
BEGIN 和 END blocks 与 Awk 在 all 输入的开头和结尾运行,例如。文件列表,因此非常适合构建标题和列映射
在 Awk 中使用 while 和 getline 可以解析命令的输出...
#!/usr/bin/awk -f
BEGIN {
for (i = 1; i < ARGC; i++) {
if (ARGV[i] ~ "^--directory=") {
_directory = substr(ARGV[i], 13)
delete ARGV[i]
}
if (ARGV[i] ~ "^--name=") {
_name = substr(ARGV[i], 8)
delete ARGV[i]
}
# ... perhaps add other args to parse
}
# ... build/print header maybe
}
{
cmd = "find " _directory " -name " _name " 2>/dev/null"
while (( cmd | getline _line ) > 0) {
print "_line ->", _line
# ... do some fancy formatting, use a built-in, or another command
# to build desired column output from find results
}
close(cmd)
# ...
}
当你想编写一个 Bash 脚本时,这可能非常方便,该脚本只是一个带有一些自定义解析的命令的包装器。
有很多方便的内置 Awk 函数(GAwk 更是如此),例如。 split、length,并且可以通过 Awk 脚本中的 function 关键字添加更多内容。
数组/字典变量也可以使用 Awk,例如...
BEGIN {
for (i = 1; i < ARGC; i++) {
if (ARGV[i] ~ "^--from=") {
_custom_args["from"] = substr(ARGV[i], 8)
delete ARGV[i]
} else if (ARGV[i] ~ "^--till=") {
_custom_args["till"] = substr(ARGV[i], 8)
delete ARGV[i]
}
}
}
{
# ...
}
但是(如果我没记错的话)应该避免像 _something[0,1] 这样的多维数组,因为在 Awk 中这样的事情真的是 _something["0,1"]
使用 Awk 将列打印为格式良好的表格有点棘手,但也可以通过 printf 格式化选项来实现...
#!/usr/bin/awk -f
BEGIN {
printf("%-8s %-13s %s\n", "Owner", "RepoName", "CreatedDate")
}
本质上,%-8s 告诉 Awk 至少保留 8 个空格字符,而不管 "Owner"、%-13s 保留 13 和 - 的字符串长度如何,告诉 Awk 用字符串右侧/末尾的分隔符。
为了禁止更长的刺痛printf 结合%.<n> 可能有用...
#!/usr/bin/awk -f
BEGIN {
printf("%.3s %-13s %s\n", "Owner", "RepoName", "CreatedDate")
}
如果您遇到问题,请随时发表评论,我会再次尝试提供更多提示。