在awk中返回两个变量

Ang*_*.47 5 bash shell awk

目前这就是我正在做的事情

ret=$(ls -la | awk '{print $3 " "  $9}')
usr=$(echo $ret | awk '{print $1}')
fil=$(echo $ret | awk '{print $2}')
Run Code Online (Sandbox Code Playgroud)

问题是我没有运行lsim运行需要时间的命令,所以你可以理解逻辑.

有没有办法我可以设置返回值来设置两个外部值,所以像

ls -la | awk -r usr=x -r fil=y '{x=$3; y=$9}'
Run Code Online (Sandbox Code Playgroud)

这样命令将运行一次,我可以将它最小化为一行

bob*_*bob 5

它不漂亮,但如果你真的需要在一行中完成这个,你可以使用awk/ bash的高级元编程功能:)

eval $(ls -la | awk '{usr = $3 " " usr;fil = $9 " " fil} END{print "usr=\""usr"\";fil=\""fil"\""}')
Run Code Online (Sandbox Code Playgroud)

打印:

echo -e $usr
echo -e $fil
Run Code Online (Sandbox Code Playgroud)

就个人而言,我坚持你所拥有的东西 - 与上述相比,它更具可读性和性能开销很小:

$time <three line approach>

real    0m0.017s
user    0m0.006s
sys     0m0.011s

$time <one line approach>
real    0m0.009s
user    0m0.004s
sys     0m0.007s
Run Code Online (Sandbox Code Playgroud)


oli*_*bre 4

解决方法使用read

usr=""
fil=""
while read u f; do usr="$usr\n$u"; fil="$fil\n$f"; done < <(ls -la | awk '{print $3 " "  $9}')
Run Code Online (Sandbox Code Playgroud)

对于性能问题,您可以使用<<<,但如果返回的文本很大,请避免使用:

while read u f; do usr="$usr\n$u"; fil="$fil\n$f"; done <<< $(ls -la | awk '{print $3 " "  $9}')
Run Code Online (Sandbox Code Playgroud)

一种更便携的方式受到@WilliamPursell的回答的启发:

$ usr=""
$ fil=""
$ while read u f; do usr="$usr\n$u"; fil="$fil\n$f"; done << EOF
> $(ls -la | awk '{print $3 " "  $9}')
> EOF
Run Code Online (Sandbox Code Playgroud)