2011-03-24 31 views
17

表示的文件的特定行可能,這可能是一個明顯的事情,但它逃脫了我,因爲它可能可以用我目前還不知道的更簡單的方式完成。 說有一個「文件」,我只想查看該文件的行號「X」上的內容,解決方案是什麼?查看數字

這是我能想到的:

head -X < file | tail -1 
sed -n Xp < file 

有從一組標準的UNIX/GNU/Linux的文本工具/ utils的任何東西(或任何其他方式)?

+3

基本上相當於'sed':'echo Xp | ed -s文件' – 2011-03-24 12:25:12

+2

'awk'NR == X'文件' – 2011-03-24 12:27:19

回答

2

AWK一行代碼:

awk "NR==$X" file 

bash的循環:

for ((i=1; i<=X; i++)); do 
    read l 
done < file 
echo "$l" 
24

sed -n 'Xp' theFile,其中X是你的行號和theFile是您的文件。

+0

爲什麼這是downvoted?這是最便攜,最簡單和最有效的方式。一個甚至不需要報價。 – matja 2011-10-22 19:46:31

+1

@matja:因爲它已經在原文中。 – XXL 2011-10-28 08:44:21

+1

@XXL - 是嗎?問題是這是最好的答案,所以應該這樣投票。 – fig 2013-12-19 15:27:53

1

只需用vi

vi file 

當文件類型

:X 

其中X是你想看到

但是行號,sed的-n XP文件是一個好的方法,如果你真的只想看到一行

+0

您可以直接進入該行 - 正如其他答案所示 – 2011-10-22 19:15:45

6

在vi:

vi +X filename 
在EMACS

emacs +X filename 

在殼

nl -ba -nln filename| grep '^X ' 

可以使用上下文的grep cgrep代替grep到見上文和匹配線以下一些線..


實施例:

打印只是一個行:

$ nl -ba -nln active_record.rb | grep '^111 ' 
111  module ConnectionAdapters 

與上下文:

$ nl -ba -nln active_record.rb | grep -C 2 '^111 ' 
109  end 
110  
111  module ConnectionAdapters 
112   extend ActiveSupport::Autoload 
113  

上下文控制在grep檢查man grep

Context Line Control 
     -A NUM, --after-context=NUM 
       Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. 

     -B NUM, --before-context=NUM 
       Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. 

     -C NUM, -NUM, --context=NUM 
       Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given.