如何从shell脚本中的unix命令输出中获取特定行中的特定单词?

时间:2013-05-09 09:00:19

标签: linux shell unix aix

我想在ex ls -al的shell脚本中运行命令,我需要提取第5行的第3个字。有人可以帮忙吗?

我目前拥有的是:

str = $(ls -al foo | cut -d" " -f3) 

这是将所有单词存储在第3个字段中,但我无法从第5行获取该单词。

任何人都可以告诉我如何获得特定的产品线或更优化的解决方案。

2 个答案:

答案 0 :(得分:3)

尝试str=$(ls -al foo | awk 'NR==5{print $3;exit}')ls命令输出不适合解析。此外,cut将连续空格计为单独的字段,因此使用cut标识单词总是存在风险

实验: -

[[bash_prompt$]]$ ls -al foo
total 12
drwxr-xr-x  2 abasu synopsys 4096 2013-05-09 15:11 .
drwxr-xr-x  9 abasu synopsys 4096 2013-05-09 15:11 ..
-rw-r--r--  1 abasu synopsys    0 2013-05-09 15:08 a
-rw-r--r--  1 abasu synopsys    0 2013-05-09 15:08 b
-rw-r--r--  1 abasu synopsys 1362 2013-05-09 15:11 c
-rw-r--r--  1 abasu synopsys    0 2013-05-09 15:08 d
-rw-r--r--  1 abasu synopsys    0 2013-05-09 15:08 e
-rw-r--r--  1 abasu synopsys    0 2013-05-09 15:08 f
[[bash_prompt$]]$ ls -al foo | awk 'NR==5{print $3;exit}'
abasu
[[bash_prompt$]]$ ls -al foo | awk 'NR==6{print $5;exit}'
1362
[[bash_prompt$]]$ str=$(ls -al foo | awk 'NR==6{print $5;exit}')  #for 6th line,5th word
[[bash_prompt$]]$ echo $str
1362

答案 1 :(得分:2)

只需将命令更改为:

ls -al |head -5|tail -1|cut -d" " -f3