awk分割问题
我编写了一个小脚本,使用 awk 'split' 命令来获取当前目录名称。
echo $PWD
我需要将“8”替换为拆分操作结果的令牌数量。 // 如果 PWD = /home/用户名/bin.我正在尝试将“bin”放入包中。
package="`echo $PWD | awk '{split($0,a,"/"); print a[8] }'`"
echo $package
您能否告诉我用什么来代替“print a[8]”才能使脚本适用于任何目录路径?
-萨钦
I wrote a small script, using awk 'split' command to get the current directory name.
echo $PWD
I need to replace '8' with the number of tokens as a result of the split operation.
// If PWD = /home/username/bin. I am trying to get "bin" into package.
package="`echo $PWD | awk '{split($0,a,"/"); print a[8] }'`"
echo $package
Can you please tell me what do I substitute in place of 'print a[8]' to get the script working for any directory path ?
-Sachin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不需要 awk。如果您总是想要路径中的最后一个目录,只需执行以下操作:
上面的命令还有一个额外的好处,即不为外部二进制文件创建任何子 shell 和/或分支。这都是原生 POSIX shell 语法。
You don't need awk for that. If you always want the last dir in a path just do:
The above has the added benefit of not creating any subshells and/or forks to external binaries. It's all native POSIX shell syntax.
您可以使用
print a[length(a)]
但最好避免拆分并使用自定义字段分隔符和$NF
:但在这种特定情况下,您应该使用 <代码>基本名称:
You could use
print a[length(a)]
but it's better to avoid splitting and use custom fields separator and$NF
:But in that specific case you should rather use
basename
:其他答案是执行您想要完成的功能的更好替代品。但是,这是您问题的具体答案:
split()
返回结果元素的数量。The other answers are better replacements to perform the function you're trying to accomplish. However, here is the specific answer to your question:
split()
returns the number of resulting elements.