开发者

awk split question

I wrote a small script, using awk 'split' command to get the current directory name.

echo $PWD

I need to replace '8' with the num开发者_StackOverflow社区ber 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


You don't need awk for that. If you always want the last dir in a path just do:

#!/bin/sh

cur_dir="${PWD##*/}/"
echo "$cur_dir"

The above has the added benefit of not creating any subshells and/or forks to external binaries. It's all native POSIX shell syntax.


You could use print a[length(a)] but it's better to avoid splitting and use custom fields separator and $NF:

echo $PWD | awk -F/ '{print $NF}'

But in that specific case you should rather use basename:

basename "$PWD"


The other answers are better replacements to perform the function you're trying to accomplish. However, here is the specific answer to your question:

package=$(echo $PWD | awk '{n = split($0,a,"/"); print a[n] }')
echo "$package"

split() returns the number of resulting elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜