开发者

view a particular line of a file denoted by a number

开发者 https://www.devze.com 2023-02-19 16:50 出处:网络
Okay, this is probably an evident thing but it escapes me, as in it could probably be done in a much simpler way that I\'m not aware of, so far..

Okay, this is probably an evident thing but it escapes me, as in it could probably be done in a much simpler way that I'm not aware of, so far.. Say there's a "file" and I want to view only what's on line number "X" of that file, what would be the solution?

here's what i can think of:

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

is there anything else (or any other way) from the standard set of u开发者_Python百科nix/gnu/linux text-tools/utils?


sed -n 'Xp' theFile, where X is your line number and theFile is your file.


in vi:

vi +X filename

in EMACS:

emacs +X filename

in the shell:

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

you can use context grep cgrep instead of grep to see some lines above and below the matching line..


EXAMPLES:

print just that one line:

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

with context:

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

for context control in grep check 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.


awk one-liner:

awk "NR==$X" file

bash loop:

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


Just use vi

vi file

When in the file type

:X

where X is the line number you want to see

However, the sed -n Xp file is a good way if you really only want to see the one line

0

精彩评论

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

关注公众号