Modulo 4.1 - Uso esencial de vi o vim en entornos sin GUI

OIP.srEttRQys-jrpRLCHy_IAgHaE8 (474×316) Editar archivos de configuración o scripts usando únicamente el editor vi, presente en cualquier sistema Linux, incluso en modo rescate o instalaciones mínimas.


Introducción operativa

vi (y su mejora vim) es el editor de texto siempre disponible en entornos empresariales, servidores remotos o instalaciones mínimas. A diferencia de otros editores como nano, no muestra ayuda en pantalla ni trabaja en modo lineal: usa modos de operación.

Saber usar vi es una habilidad de supervivencia crítica para todo administrador. Incluso si prefieres otros editores, siempre habrá situaciones donde solo vi estará disponible (modo rescate, recovery shell, chroot, etc.).


🧩 Modo técnico-operativo: los 3 modos clave de vi

  • Modo normal (comando): es el modo por defecto. Desde aquí se navega, se borra, se copia, se pega, se ejecutan comandos.

  • Modo inserción: para escribir texto. Se accede con i, a, o, etc.

  • Modo línea de comandos: para guardar, salir, buscar, reemplazar. Se accede con : (dos puntos).


Comandos de supervivencia (uso mínimo funcional)

Acción Tecla o Comando
Ingresar texto i (insertar antes del cursor), a (después del cursor), o (nueva línea abajo)
Volver a modo normal Esc
Guardar :w
Salir :q
Guardar y salir :wq o ZZ
Salir sin guardar :q!
Borrar línea dd
Deshacer último cambio u
Rehacer Ctrl + r
Copiar línea yy
Pegar p
Moverse h izq, j abajo, k arriba, l der
Buscar /palabra luego n para siguiente

🧪 Práctica paso a paso (mínimo viable)

  1. Crear archivo:

    vi hola.txt
  2. Insertar texto:

    • Presiona i → escribe “Hola mundo” → presiona Esc.
  3. Guardar y salir:

    • Escribe :wq → Enter.
  4. Abrir y editar:

    • Ejecuta vi hola.txt

    • Presiona j para bajar línea, o para nueva línea.

    • Escribe “Editando con vi”, luego Esc.

    • Guarda con :w.

  5. Salir sin guardar:

    • Modifica algo, luego Esc :q! → Enter.
  6. Practica errores comunes:

    • Intenta escribir :wq sin presionar Esc antes (verás que el texto se escribe).

    • Ahora repite correctamente (Esc, luego :wq).


⚠️ Errores comunes y cómo sobrevivir

  • Teclado no responde como esperas: Presiona varias veces Esc, vuelve a terreno seguro.

  • No sabes en qué modo estás: Esc te lleva a modo normal. Desde ahí puedes moverte o salir.

  • Archivo no guarda: Revisa permisos. Usa sudo vi archivo.txt si necesitas privilegios.

  • Aparece .swp: significa que hay una sesión anterior. Usa vim -r archivo.txt para recuperar, o elimina el .swp si estás seguro.


Recomendación visual para el curso

  • Captura 1: vi en modo inserción (texto visible, sin comandos).

  • Captura 2: vi en modo normal ejecutando :wq.

  • Captura 3: mensaje típico de .swp y cómo continuar.


✅ Criterios de evaluación

  • Abre, edita y guarda un archivo con vi.

  • Sale de vi sin corromper el contenido.

  • Identifica modos de operación correctamente.

  • Demuestra uso de al menos 5 comandos básicos (i, Esc, :wq, dd, u).

  • Se siente confiado para editar archivos críticos si solo tiene vi.


❓ Preguntas de repaso

  • ¿Qué haces si nano no está instalado?

  • ¿Cómo guardas sin salir? ¿Y cómo sales sin guardar?

  • ¿Qué significa estar en modo normal?

  • ¿Cuál es la diferencia entre i, a y o?

  • ¿Cómo recuperas un archivo tras un cierre inesperado?


Se recomienda ampliamente usar

vimtutor

este es un tutorial de incluida por vim, solo se ejecuta en la terminal y realizar las intrucciones.

  1. The cursor is moved using either the arrow keys or the hjkl keys.
         h (left)       j (down)       k (up)       l (right)

  2. To start Vim from the shell prompt type:  vim FILENAME <ENTER>

  3. To exit Vim type:     <ESC>   :q!   <ENTER>  to trash all changes.
             OR type:      <ESC>   :wq   <ENTER>  to save the changes.

  4. To delete the character at the cursor type:  x

  5. To insert or append text type:
         i   type inserted text   <ESC>         insert before the cursor
         A   type appended text   <ESC>         append after the line

NOTE: Pressing <ESC> will place you in Normal mode or will cancel
      an unwanted and partially completed command.

  1. To delete from the cursor up to the next word type:    dw
  2. To delete from the cursor to the end of a line type:    d$
  3. To delete a whole line type:    dd

  4. To repeat a motion prepend it with a number:   2w
  5. The format for a change command is:
               operator   [number]   motion
     where:
       operator - is what to do, such as  d  for delete
       [number] - is an optional count to repeat the motion
       motion   - moves over the text to operate on, such as  w (word),
                  $ (to the end of line), etc.

  6. To move to the start of the line use a zero:  0

  7. To undo previous actions, type:           u  (lowercase u)
     To undo all the changes on a line, type:  U  (capital U)
     To undo the undo's, type:                 CTRL-R
'

                               Lesson 3 SUMMARY

  1. To put back text that has just been deleted, type   p .  This puts the
     deleted text AFTER the cursor (if a line was deleted it will go on the
     line below the cursor).

  2. To replace the character under the cursor, type   r   and then the
     character you want to have there.

  3. The change operator allows you to change from the cursor to where the
     motion takes you.  eg. Type  ce  to change from the cursor to the end of
     the word,  c$  to change to the end of a line.

  4. The format for change is:

         c   [number]   motion

                               Lesson 4 SUMMARY

  1. CTRL-G  displays your location in the file and the file status.
             G  moves to the end of the file.
     number  G  moves to that line number.
            gg  moves to the first line.

  2. Typing  /  followed by a phrase searches FORWARD for the phrase.
     Typing  ?  followed by a phrase searches BACKWARD for the phrase.
     After a search type  n  to find the next occurrence in the same direction
     or  N  to search in the opposite direction.
     CTRL-O takes you back to older positions, CTRL-I to newer positions.

  3. Typing  %  while the cursor is on a (,),[,],{, or } goes to its match.

  4. To substitute new for the first old in a line type    :s/old/new
     To substitute new for all 'old's on a line type       :s/old/new/g
     To substitute phrases between two line #'s type       :#,#s/old/new/g
     To substitute all occurrences in the file type        :%s/old/new/g
     To ask for confirmation each time add 'c'             :%s/old/new/gc

  5.  :!command  executes an external command.

      Some useful examples are:
         (Windows)        (Unix)
          :!dir            :!ls            -  shows a directory listing.
          :!del FILENAME   :!rm FILENAME   -  removes file FILENAME.

  6.  :w FILENAME  writes the current Vim file to disk with name FILENAME.

  7.  v  motion  :w FILENAME  saves the Visually selected lines in file
      FILENAME.

  8.  :r FILENAME  retrieves disk file FILENAME and puts it below the
      cursor position.

  9.  :r !dir  reads the output of the dir command and puts it below the
      cursor position.

                               Lesson 6 SUMMARY

  1. Type  o  to open a line BELOW the cursor and start Insert mode.
     Type  O  to open a line ABOVE the cursor.

  2. Type  a  to insert text AFTER the cursor.
     Type  A  to insert text after the end of the line.

  3. The  e  command moves to the end of a word.

  4. The  y  operator yanks (copies) text,  p  puts (pastes) it.

  5. Typing a capital  R  enters Replace mode until  <ESC>  is pressed.

  6. Typing ":set xxx" sets the option "xxx".  Some options are:
        'ic' 'ignorecase'       ignore upper/lower case when searching
        'is' 'incsearch'        show partial matches for a search phrase
        'hls' 'hlsearch'        highlight all matching phrases
     You can either use the long or the short option name.

  7. Prepend "no" to switch an option off:   :set noic