Wednesday, July 2, 2014

Linux Vi
The traditional approach to find lines not matching a pattern is using the :v command:

A neat trick when working with a large log file where you want to filter out as many irrelevant lines as possible before you get started on your real search is to save the file under a temporary name and delete all non-matching lines there:

:sav junk.log
You are now are editing a clone of your original file with all lines not matching "warning" removed and you can edit it at will.This will find everything but the regular expression you have specified. For example, if we want to find all the lines not containing the word 'foo', do:

Here is an example: When examining a log file, you might only be interested in lines not containing the word "Warning", so the search command is:

To match all words except 'foo', use:

\< Start-of-word
\(Foo\>\) The atom 'Foo' followed by end-of-word
\@! Match (with zero length) when the previous atom doesn't match.
\k\+ Match one or more Keywords
\> Match end-of-word.
The use of \@! can be very tricky. According to the Vim help files, it is often easier to use \@<! instead. For example, to find all 'bar' strings unless they are part of 'foobar', use the following (non-magic):

If we want to find a more complex regular expression on multiple lines, like all the lines which do not begin with 'foo' with 'bar' somewhere else and the word 'magic' at the end of the next line, do:

As well as the suggestions for \c and ignorecase, I find the smartcase very useful. If you search for something containing uppercase characters, it will do a case sensitive search; if you search for something purely lowercase, it will do a case insensitive search. You can use \c and \C to override this:
:set ignorecase
:set smartcase
/copyright      " Case insensitive
/Copyright      " Case sensitive
/copyright\C    " Case sensitive
/Copyright\c    " Case insensitive
Worth noting that for smartcase to work, you also need set ignorecas

:set ic
To go back to case-sensitive searches use:
:set noic
To change any session settings in vi, you use the :set command. To display a list of the options and settings, use the :set all command.
:set autoindent
:set shiftwidth=4
you can use the :set ignorecase command. Turn case sensitivity back on using :set noignorecase. You can also use shorthand versions (:set ic and :set noic).
Compound searches
f you want to search for the first occurrence of a pattern or string where it follows another regardless of whether both patterns or strings exist on the same line, you can use a compound search by specifying both search commands separated by a semi-colon (;). For example, to search for the first occurrence of the string echo where it follows the string {file}+1, you would use /{file}+1/;/echo/.

You can tell vi to place a bookmark at a point in a file by pressing the M key followed by another alphabetic character that denotes the bookmark reference. Therefore, you have up to 26 bookmarks named a to z. To return to the previous bookmark, press the back tick (`) followed by the bookmark reference alphabetic character.
For example, after pressing the MA keys, you would save the current cursor position into a bookmark named a. Whenever you want to return to that cursor position later in the editing session, you simply press the `A keys. To flip between the current bookmark and the previous one, you can use the double back tick (``) command sequence.
You can switch the case of the alpha character underneath your cursor in vi the tilde key (~). Doing so shifts from lowercase to uppercase and vice versa. Holding down the key rolls over each character in the line, flipping the case of any alpha characters the editor comes across. You can enter a numeric character prior to the tilde to denote how many alpha characters you want to change.
- shift+`

You probably know that you can execute commands in a shell within vi by typing :!command, where command is the UNIX command that you want to execute—for example, :!pwd to show the present working directory your editing session is in—and then pressing Enter.
However, you can also send a section of your file as the standard input to a UNIX command of your choice and have the same section in your editing buffer replaced by the resulting output. For example, if you wanted to sort the entire file while remaining in the vi session, you would type :1,$!sort to instruct vi to pass lines 1 through the end of the file ($) into the sort command, replacing the specified section with the output, and then press Enter.
Alternatively, you can prefix the shell command with the number of lines you want it to operate on from the current cursor. To do so type a numeric character specifying the number of lines followed by double exclamation marks (!!) followed by the UNIX command.
4!!awk '{print "New text",$0}' - not work
You start recording by q<letter> and you can end it by typing q again.
Recording is a really useful feature of Vim.
It records everything you type. You can then replay it simply by typing @<letter>. Record search, movement, replacement...
How To Record and Play
Quincy's answer is fine, but there's an exact way to do this which doesn't require editing the buffer:
This will print a message like 3 matches on 2 lines, and no changes will be made to your buffer.
The n flag makes the :substitute command print the number of matches instead of performing an actual substitution; the g flag enables reporting of multiple matches per line.

Another thing that might be useful to your use case is to print all lines that match a pattern:
which can be shortened to:
This is one of the simplest uses of the :global command (which is mind-bogglingly powerful). It will simply print out all of the lines that match pattern, and then you press Enter or type another command to make it go away.
A bit of trivia: This command is the origin of the name grep, as it would commonly be described as g/re/p, where re stands for "regular expression".
:%s/pattern//n The n flag in the end tells :s command to report the number of matches and not actually substitute. Read :h :s_flags for more details.
% is the range over which the :s command (short for :substitute) will be run. % itself is short for the range :1,$, which means Line 1 to the last line in the buffer.
A buffer is the in-memory text of a file ... [which is] loaded into memory for editing. The original file remains unchanged until you write the buffer to the file.
That is, a buffer represents the actual loaded/working data itself.
set nu - show line number
CTRL-E   Scroll window [count] lines downwards in the buffer.
   Mnemonic: Extra lines.
<PageDown> or    *<PageDown>* *CTRL-F*
CTRL-F   Scroll window [count] pages Forwards (downwards) in
   the buffer. 
CTRL-D   Scroll window Downwards in the buffer.  The number of
   lines comes from the 'scroll' option (default: half a

<PageUp> or     *<PageUp>* *CTRL-B*
CTRL-B   Scroll window [count] pages Backwards (upwards) in the
CTRL-U   Scroll window Upwards in the buffer.  The number of
   lines comes from the 'scroll' option (default: half a
CTRL-Y   Scroll window [count] lines upwards in the buffer.

6. Scrolling with a mouse wheel    *scroll-mouse-wheel*

vi/vim delete commands and examples | vi vim delete lines to end |
Delete all blank lines
:g will execute a command on lines which match a regex. The regex is 'blank line' and the command is :d (delete)

x   - delete current character

dw  - delete current word
dd  - delete current line
5dd - delete five lines

d$  - delete to end of line
d0  - delete to beginning of line

delete to beginning of file

delete to end of file

If all lines in the file are to be deleted, this vi command specifies the range of deletion:

vi -r filename is used to recover a file from .swp file
:e "file name"

Copy and paste text with vi or vim | a Tech-Recipes Tutorial
The command ‘Y’ or ‘yy’ copies (yanks) one or more lines. To copy one line, two lines, 10 lines, and all lines to the end of the file, respectively:
Y 2Y

To paste the text contained in the buffer above (uppercase P) or below the current cursor position (lowercase p), respectively:
P p

It is also possible to yank text within a line. The following commands yank text from the current cursor position to the end of the word and the end of the line, respectively:
yw y$

Lower case p pastes after the cursor position and upper case P pastes before.

Paste will also work with deleted text, either lines or parts of lines. Be careful not to execute any other commands prior to pasting as this will empty the buffer.

 13 Vi Editor Interview Questions And Answers
/text: it will search for the string. after pressing enter it takes u to that text location.
How to enter from command mode to insertion mode using Vi Editor?
Ans: a,i
What is the difference between ZZ and :wq commands in Vi Editor?
ZZ is the command mode comand in uix to save and quit file.
:wq is the execute command mode command to save and quit file.

How to append a file to current file using Vi Editor?
:r file2
If you are working in file1 and want to append file2, than place the cursor where you want to append the new file and use the following command<
How to go 10 number line in command mode directly ?

Which command is used to replace many characters in Vi Editor?
change command can be used to change a word/line.
cw change word forward
cb change word backward
c$ change from cursor to end of line
cL change from current line to and of screen
cG change from current line to and of file

or if you want to replace all occurence of some specific character

Basic vi Commands
To Exit vi
*:x<Return>quit vi, writing out modified file to file named in original invocation
:wq<Return>quit vi, writing out modified file to file named in original invocation
:q<Return>quit (or exit) vi
*:q!<Return>quit vi even though latest changes have not been saved for this vi call

Moving the Cursor
*j or <Return>
  [or down-arrow]
move cursor down one line
*k [or up-arrow]move cursor up one line
*h or <Backspace>
  [or left-arrow]
move cursor left one character
*l or <Space>
  [or right-arrow]
move cursor right one character
*0 (zero)move cursor to start of current line (the one with the cursor)
*$move cursor to end of current line
wmove cursor to beginning of next word
bmove cursor back to beginning of preceding word
:0<Return> or 1Gmove cursor to first line in file
:n<Return> or nGmove cursor to line n
:$<Return> or Gmove cursor to last line in file

Inserting or Adding Text
*iinsert text before cursor, until <Esc> hit
Iinsert text at beginning of current line, until <Esc> hit
*aappend text after cursor, until <Esc> hit
Aappend text to end of current line, until <Esc> hit
*oopen and put text in a new line below current line, until <Esc> hit
*Oopen and put text in a new line above current line, until <Esc> hit

Changing Text
*rreplace single character under cursor (no <Esc> needed)
Rreplace characters, starting with current cursor position, until <Esc> hit
cwchange the current word with new text,
starting with the character under cursor, until <Esc> hit
cNwchange N words beginning with character under cursor, until <Esc> hit;
  e.g., c5w changes 5 words
Cchange (replace) the characters in the current line, until <Esc> hit
ccchange (replace) the entire current line, stopping when <Esc> is hit
Ncc or cNcchange (replace) the next N lines, starting with the current line,
stopping when <Esc> is hit

Saving and Reading Files

:r filename<Return>read file named filename and insert after current line
(the line with cursor)
:w<Return>write current contents to file named in original vi call
:w newfile<Return>write current contents to a new file named newfile
:12,35w smallfile<Return>write the contents of the lines numbered 12 through 35 to a new file named smallfile
:w! prevfile<Return>write current contents over a pre-existing file named prevfile

what are the different modes in vi editor?
Command mode
This is the default when you enter vi. In command mode, most letters, or short sequences of letters, that you type will be interpreted as command. If you press Esc when you're in command mode, your terminal will beep at you. This is a very good way to tell when you're in command mode.

Insert mode
In insert mode, whatever you type is inserted in the file at the cursor position. Type a (lowercase letter a, for append) to enter insert mode from command mode; press Esc
to end insert mode, and return to command mode.

Last Line mode
Use line mode to enter line oriented commands. To enter line mode from command mode, type a colon ( : ). Your cursor moves to the bottom of the screen, by a colon prompt. Type a line mode command, then press Enter. Any sensible command from the Unix line editor ex will work, and a few are good to know about. These commands are indicated in this handout by a colon in front of the command. Each time you use a line mode command, you must type a colon to enter line mode, then type the command by the colon prompt at the bottom of the screen, then press Enter when you finish typing the command. (The search commands starting with / and ? work similarly).

No comments:

Post a Comment


Review (561) System Design (304) System Design - Review (196) Java (179) Coding (75) Interview-System Design (65) Interview (60) Book Notes (59) Coding - Review (59) to-do (45) Linux (40) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (29) Product Architecture (28) Big Data (27) Soft Skills (27) Concurrency (26) MultiThread (26) Miscs (25) Cracking Code Interview (24) Distributed (24) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) OOD Design (20) System Design - Practice (19) How to Ace Interview (16) Security (16) Algorithm (15) Brain Teaser (14) Google (14) Redis (14) Linux - Shell (13) Spark (13) Spring (13) Code Quality (12) How to (12) Interview-Database (12) Interview-Operating System (12) Tools (12) Architecture Principles (11) Company - LinkedIn (11) Solr (11) Testing (11) Resource (10) Search (10) Amazon (9) Cache (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Company - Uber (8) Interview - MultiThread (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Scalability (8) Trouble Shooting (8) Cassandra (7) Company - Facebook (7) Design (7) Git (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Machine Learning (7) NoSQL (7) C++ (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) API Design (4) Be Architect (4) Big Fata (4) C (4) Company Product Architecture (4) Data structures (4) Design Principles (4) Facebook (4) GeeksforGeeks (4) Generics (4) Google Interview (4) Hardware (4) JDK8 (4) Optimization (4) Product + Framework (4) Puzzles (4) Python (4) Shopping System (4) Source Code (4) Web Service (4) node.js (4) Back-of-Envelope (3) Chrome (3) Company - Pinterest (3) Company - Twiiter (3) Company - Twitter (3) Consistent Hash (3) Elasticsearch (3) GOF (3) Game Design (3) GeoHash (3) Growth (3) Guava (3) Html (3) Interview-Big Data (3) Interview-Linux (3) Interview-Network (3) Java EE Patterns (3) Javarevisited (3) Map Reduce (3) Math - Probabilities (3) Performance (3) RateLimiter (3) Resource-System Desgin (3) Scala (3) UML (3) ZooKeeper (3) geeksquiz (3) AI (2) Advanced data structures (2) AngularJS (2) Behavior Question (2) Bugs (2) Coding Interview (2) Company - Netflix (2) Crawler (2) Cross Data Center (2) Data Structure Design (2) Database-Shard (2) Debugging (2) Docker (2) Garbage Collection (2) Go (2) Hadoop (2) Interview - Soft Skills (2) Interview-Miscs (2) Interview-Web (2) JDK (2) Logging (2) POI (2) Papers (2) Programming (2) Project Practice (2) Random (2) Software Desgin (2) System Design - Feed (2) Thread Synchronization (2) Video (2) reddit (2) Ads (1) Algorithm - Review (1) Android (1) Approximate Algorithms (1) Base X (1) Bash (1) Books (1) C# (1) CSS (1) Client-Side (1) Cloud (1) CodingHorror (1) Company - Yelp (1) Counter (1) DSL (1) Dead Lock (1) Difficult Puzzles (1) Distributed ALgorithm (1) Eclipse (1) Facebook Interview (1) Function Design (1) Functional (1) GoLang (1) How to Solve Problems (1) ID Generation (1) IO (1) Important (1) Internals (1) Interview - Dropbox (1) Interview - Project Experience (1) Interview Stories (1) Interview Tips (1) Interview-Brain Teaser (1) Interview-How (1) Interview-Mics (1) Interview-Process (1) Java Review (1) Jeff Dean (1) Joda (1) LeetCode - Review (1) Library (1) LinkedIn (1) LintCode (1) Mac (1) Micro-Services (1) Mini System (1) MySQL (1) Nigix (1) NonBlock (1) Process (1) Productivity (1) Program Output (1) Programcreek (1) Quora (1) RPC (1) Raft (1) Reactive (1) Reading (1) Reading Code (1) Refactoring (1) Resource-Java (1) Resource-System Design (1) Resume (1) SQL (1) Sampling (1) Shuffle (1) Slide Window (1) Spotify (1) Stability (1) Storm (1) Summary (1) System Design - TODO (1) Tic Tac Toe (1) Time Management (1) Web Tools (1) algolist (1) corejavainterviewquestions (1) martin fowler (1) mitbbs (1)

Popular Posts