2011-12-22 61 views
2

我想读取文件的第二行:阅读,直到空间

$(sed -n 2p $file) 

这工作得很好,但我想读行,直到第一个空间。 任何想法如何做到这一点?

+0

你是否在使用$(...)命令替换原因?通常我们会看到myDate =“$(sed ... file)”。祝你好运。 – shellter 2011-12-22 17:22:54

+0

已添加不使用管道的备用解决方案。 – 2011-12-22 17:37:36

回答

2

如何:

$ sed -n 2p $file | cut -d " " -f1 
1

你可能想尝试这样的事:

$(sed -n '2s/ .*//p' $file) 

这就像你的,除了s命令取代后(.*)的空间和任何与没有任何东西,即删除该行的其余部分。

0

您可以这样做,将您的行分割成数组,然后每次只读一个单词。

while IFS=" " read -a word; do # storing the line separated by space in an array 
    echo "${word[0]}"; # calling the first array element which is indexed at 0 
done < <(head -n 2 file | tail -n 1) # process substitution of fetching only second line 

测试:

[jaypal:~/Temp] cat file 
a 212 
b 323 
c 23 
d 45 
e 54 
f 102 

[jaypal:~/Temp] while IFS=" " read -a word; do 
echo "${word[0]}"; 
done < <(head -n 2 file | tail -n 1) 
b 

或者,如果你只是想用一个班轮一个快速的解决方案,然后下面的工作就好了 -

awk 'NR==2{print $1}' filename 

测试:

[jaypal:~/Temp] awk 'NR==2{print $1}' file 
b