GNU/Linux >> Tutoriales Linux >  >> Linux

Linux para principiantes:10 comandos más para manipular archivos

En caso de que se haya perdido el primer segmento de esta serie de dos partes, analizamos 10 comandos para que pueda comenzar con la terminal. Ahora, vamos a explorar 10 comandos adicionales que puede usar para continuar con su recorrido por la línea de comandos. Específicamente, quiero ver los comandos que se usan para manipular archivos. Vamos a copiar, mover y renombrar archivos, además de algunos comandos para leer archivos de diferentes maneras.

Comandos para saber

1. cp archivo1 archivo2

La copia El comando se utiliza para copiar el contenido de un archivo a otro. También puede usar este comando para copiar un archivo de un directorio a otro.

[tcarrigan@server community_content]$ ls -l
total 36
-rw-rw-r--. 1 tcarrigan tcarrigan    5 Feb  6  2020 article
-rw-rw-r--. 1 root      tcarrigan    5 Feb  6  2020 article2
-rw-rw-r--. 1 root      tcarrigan    5 Feb  6  2020 article3
-rw-rw-r--. 1 tcarrigan tcarrigan    5 Feb  6  2020 article4
-rw-rw-r--. 1 tcarrigan tcarrigan 6404 Apr  7  2020 podman_pulling
-rw-rw-r--. 1 tcarrigan tcarrigan 8824 Apr  7  2020 real_sysadmins
[tcarrigan@server community_content]$ cp podman_pulling article
[tcarrigan@server community_content]$ ls -l
total 40
-rw-rw-r--. 1 tcarrigan tcarrigan 6404 Oct 26 19:11 article
-rw-rw-r--. 1 root      tcarrigan    5 Feb  6  2020 article2
-rw-rw-r--. 1 root      tcarrigan    5 Feb  6  2020 article3
-rw-rw-r--. 1 tcarrigan tcarrigan    5 Feb  6  2020 article4
-rw-rw-r--. 1 tcarrigan tcarrigan 6404 Apr  7  2020 podman_pulling
-rw-rw-r--. 1 tcarrigan tcarrigan 8824 Apr  7  2020 real_sysadmins

Como ves, copié el podman_pulling contenido del artículo al artículo expediente. Ahora, la otra cosa que puede hacer con este comando es copiar un archivo existente en otro directorio. Por ejemplo, si quisiera copiar el podman_pulling artículo a mi directorio de inicio, haría algo como esto:

[tcarrigan@server community_content]$ cp podman_pulling /home/tcarrigan/
** Navigate to /home/tcarrigan **
[tcarrigan@server ~]$ ls -l
total 8
drwxrwxr-x. 4 tcarrigan tcarrigan   50 Feb  6  2020 article_submissions
drwxr-xr-x. 2 tcarrigan tcarrigan    6 Jan 27  2020 Desktop
drwxr-xr-x. 2 tcarrigan tcarrigan    6 Jan 27  2020 Documents
drwxr-xr-x. 2 tcarrigan tcarrigan    6 Jan 27  2020 Downloads
drwxr-xr-x. 2 tcarrigan tcarrigan    6 Jan 27  2020 Music
drwxr-xr-x. 2 tcarrigan tcarrigan    6 Jan 27  2020 Pictures
-rw-rw-r--. 1 tcarrigan tcarrigan 6404 Oct 26 19:17 podman_pulling
drwxr-xr-x. 2 tcarrigan tcarrigan    6 Jan 27  2020 Public
drwxr-xr-x. 2 tcarrigan tcarrigan    6 Jan 27  2020 Templates
drwxr-xr-x. 2 tcarrigan tcarrigan    6 Jan 27  2020 Videos

Puedes ver que podman_pulling ya está disponible en mi /home/tcarrigan directorio.

[ También te pueden interesar: 10 comandos prácticos de systemd:una referencia ]

2. mv archivo1 archivo2

El movimiento El comando permite a un usuario mover o cambiar el nombre de un archivo. Para mover un archivo, usaría lo siguiente:

[tcarrigan@server ~]$ mv podman_pulling article_submissions/my_articles/
[tcarrigan@server ~]$ ls -l article_submissions/my_articles/
total 20
-rw-rw-r--. 1 tcarrigan tcarrigan 4442 Apr  7  2020 Creating_physical_volumes
-rw-rw-r--. 1 tcarrigan tcarrigan 2744 Apr  7  2020 Creating_volume_groups
-rw-rw-r--. 1 tcarrigan tcarrigan 6404 Oct 26 19:17 podman_pulling

Moví el podman_pulling artículo de mi directorio de inicio a /article_submissions/my_articles . Ahora, digamos que necesitamos cambiar el nombre del artículo de "podman_pulling " a "podman sin raíces ." ¿Cómo haríamos eso?

[tcarrigan@server my_articles]$ mv podman_pulling rootless_podman
[tcarrigan@server my_articles]$ ls -l
total 20
-rw-rw-r--. 1 tcarrigan tcarrigan 4442 Apr  7  2020 Creating_physical_volumes
-rw-rw-r--. 1 tcarrigan tcarrigan 2744 Apr  7  2020 Creating_volume_groups
-rw-rw-r--. 1 tcarrigan tcarrigan 6404 Oct 26 19:17 rootless_podman

3. ln -s enlace de archivo

El enlace El comando en este contexto nos permitirá crear un enlace suave o un enlace simbólico a otro archivo o directorio. Para obtener más información sobre este tema, consulte mi artículo anterior, Vincular Linux . Por ahora, solo voy a demostrar cómo usar el comando de enlace suave.

[tcarrigan@server ~]$ ln -s article_submissions/community_content/podman_pulling podman_article
[tcarrigan@server ~]$ ls -l
total 0
drwxrwxr-x. 4 tcarrigan tcarrigan 50 Feb  6  2020 article_submissions
drwxr-xr-x. 2 tcarrigan tcarrigan  6 Jan 27  2020 Desktop
drwxr-xr-x. 2 tcarrigan tcarrigan  6 Jan 27  2020 Documents
drwxr-xr-x. 2 tcarrigan tcarrigan  6 Jan 27  2020 Downloads
drwxr-xr-x. 2 tcarrigan tcarrigan  6 Jan 27  2020 Music
drwxr-xr-x. 2 tcarrigan tcarrigan  6 Jan 27  2020 Pictures
lrwxrwxrwx. 1 tcarrigan tcarrigan 52 Oct 27 13:51 podman_article -> article_submissions/community_content/podman_pulling
drwxr-xr-x. 2 tcarrigan tcarrigan  6 Jan 27  2020 Public
drwxr-xr-x. 2 tcarrigan tcarrigan  6 Jan 27  2020 Templates
drwxr-xr-x. 2 tcarrigan tcarrigan  6 Jan 27  2020 Videos

Esto crea un enlace en mi directorio de inicio a /home/tcarrigan/article_submissions/community_content/podman_pulling archivo, lo que significa que puede leer podman_article , y abrirá el archivo dentro de community_content directorio.

4. tocar archivo

Usa el toque comando para crear o actualizar un archivo (aquí, estoy creando nuevo_archivo en mis_artículos directorio).

[tcarrigan@server my_articles]$ touch new_file
[tcarrigan@server my_articles]$ ls -l
total 20
-rw-rw-r--. 1 tcarrigan tcarrigan 4442 Apr  7  2020 Creating_physical_volumes
-rw-rw-r--. 1 tcarrigan tcarrigan 2744 Apr  7  2020 Creating_volume_groups
-rw-rw-r--. 1 tcarrigan tcarrigan    0 Oct 28 16:47 new_file
-rw-rw-r--. 1 tcarrigan tcarrigan 6404 Oct 26 19:17 rootless_podman

Tenga en cuenta que la marca de tiempo del archivo creado es 16:47. Ahora voy a usar el toque comando para actualizar la marca de tiempo a la hora actual (7:35 p. m.).

[tcarrigan@server my_articles]$ touch new_file 
[tcarrigan@server my_articles]$ ls -l
total 20
-rw-rw-r--. 1 tcarrigan tcarrigan 4442 Apr  7  2020 Creating_physical_volumes
-rw-rw-r--. 1 tcarrigan tcarrigan 2744 Apr  7  2020 Creating_volume_groups
-rw-rw-r--. 1 tcarrigan tcarrigan    0 Oct 28 19:35 new_file
-rw-rw-r--. 1 tcarrigan tcarrigan 6404 Oct 26 19:17 rootless_podman

5. gato> archivo

Este comando se usa para ingresar la salida estándar en un archivo. Introduciré "Hello World" en el archivo test_file .

[tcarrigan@server ~]$ cat > test_file
Hello World 

Usa Ctrl+D* para terminar de editar el archivo. Para ver su trabajo, puede usar el cat filename estándar sintaxis.

[tcarrigan@server ~]$ cat test_file 
Hello World

6. más archivo

El más El comando permitirá al usuario ver el contenido de un archivo una pantalla a la vez. Aquí vamos a ver el /article_submissions/my_articles/creating_physical_volumes archivo.

#  How to create a physical volume in Linux using LVM
by Tyler Carrigan

Physical volumes `PV` are the base 'block' that you need in order to manipulate a disk using Logical Volume Manager `LVM`. Now, let's not rush ahead. What exactly is a physical volume? What in the world i
s LVM? In short, LVM is a type of storage virtualization that allows operators far more flexibility in storage management than standard partitioning. A physical volume is any physical storage device, such
 as an Hard Disk Drive `HDD`, Solid State Drive `SSD`, or partition, that has been initialized as a physical volume with LVM. Without properly initialized physical volumes, you cannot create Volume Groups
 or logical volumes. 

So lets get started! First, there are a few considerations.

Dont try to pinpoint the exact amount of space you need down to the nearest byte. The reason for this is that LVM places labels on the physical volumes `UUID` as well as metadata storage. While this doesn
t take up very much space, understand that if you initialize a 1Gb PV, you do **not** have 1Gb of *usable* space.
** Output Omitted **

Puede ir línea por línea con Enter clave o página por página con Espacio . Otra opción útil es el -número opción que le permite especificar el número de líneas mostradas por página.

Para ver 10 líneas a la vez, puede usar more -10 filename . Puede utilizar el + firme para especificar desde qué línea comenzar:more +10 filename .

7. menos archivo

Cuanto menos comando permite al usuario la misma funcionalidad que más . Sin embargo, es más rápido porque no carga el archivo completo, sino que permite al usuario analizar el archivo con las teclas de flecha. Esto es especialmente notable en archivos de registro grandes.

[tcarrigan@server my_articles]$ sudo less /var/log/messages
Oct 26 19:50:47 server dbus-daemon[939]: [system] Activating via systemd: service name='org.freedesktop.nm_dispatcher' unit='dbus-org.freedesktop.nm-dispatcher.service' requested by ':1.15' (uid=0 pid=1155 comm="/usr/sbin/NetworkManager --no-daemon " label="system_u:system_r:NetworkManager_t:s0")
Oct 26 19:50:47 server systemd[1]: Starting Network Manager Script Dispatcher Service...
Oct 26 19:50:47 server dbus-daemon[939]: [system] Successfully activated service 'org.freedesktop.nm_dispatcher'
Oct 26 19:50:47 server systemd[1]: Started Network Manager Script Dispatcher Service.
** Output Omitted **

8. archivo principal

La cabeza El comando permite al usuario generar las primeras 10 líneas de cualquier archivo. Usaré el ejemplo de creating_physical_volumes .

[tcarrigan@server my_articles]$ head Creating_physical_volumes
#  How to create a physical volume in Linux using LVM
by Tyler Carrigan

Physical volumes `PV` are the base 'block' that you need in order to manipulate a disk using Logical Volume Manager `LVM`. Now, let's not rush ahead. What exactly is a physical volume? What in the world is LVM? In short, LVM is a type of storage virtualization that allows operators far more flexibility in storage management than standard partitioning. A physical volume is any physical storage device, such as an Hard Disk Drive `HDD`, Solid State Drive `SSD`, or partition, that has been initialized as a physical volume with LVM. Without properly initialized physical volumes, you cannot create Volume Groups or logical volumes. 

So lets get started! First, there are a few considerations.

Dont try to pinpoint the exact amount of space you need down to the nearest byte. The reason for this is that LVM places labels on the physical volumes `UUID` as well as metadata storage. While this doesnt take up very much space, understand that if you initialize a 1Gb PV, you do **not** have 1Gb of *usable* space. 

Also, although LVM allows you to create physical volumes using multiple partitions, it is recommended that you use a single partition for a PV. This is for a couple of reasons. 
[tcarrigan@server my_articles]$

9. archivo de cola

La cola El comando permite al usuario ver las últimas 10 líneas de cualquier archivo. Aquí veremos /var/log/messages .

[tcarrigan@server my_articles]$ sudo tail /var/log/messages
[sudo] password for tcarrigan:  
Oct 28 20:17:47 server org.gnome.Shell.desktop[2053]: Window manager warning: last_user_time (9080279) is greater than comparison timestamp (9080269).  This most likely represents a buggy client sending inaccurate timestamps in messages such as _NET_ACTIVE_WINDOW.  Trying to work around...
Oct 28 20:17:47 server org.gnome.Shell.desktop[2053]: Window manager warning: W1 appears to be one of the offending windows with a timestamp of 9080279.  Working around...
Oct 28 20:17:48 server dbus-daemon[948]: [system] Activating via systemd: service name='net.reactivated.Fprint' unit='fprintd.service' requested by ':1.500' (uid=0 pid=5259 comm="sudo tail /var/log/messages " label="unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023")
Oct 28 20:17:48 server systemd[1]: Starting Fingerprint Authentication Daemon...
Oct 28 20:17:49 server dbus-daemon[948]: [system] Successfully activated service 'net.reactivated.Fprint'
Oct 28 20:17:49 server systemd[1]: Started Fingerprint Authentication Daemon.
Oct 28 20:17:53 server org.gnome.Shell.desktop[2053]: Window manager warning: last_user_time (9086680) is greater than comparison timestamp (9086677).  This most likely represents a buggy client sending inaccurate timestamps in messages such as _NET_ACTIVE_WINDOW.  Trying to work around...
Oct 28 20:17:53 server org.gnome.Shell.desktop[2053]: Window manager warning: W1 appears to be one of the offending windows with a timestamp of 9086680.  Working around...
Oct 28 20:18:00 server org.gnome.Shell.desktop[2053]: Window manager warning: last_user_time (9093426) is greater than comparison timestamp (9093424).  This most likely represents a buggy client sending inaccurate timestamps in messages such as _NET_ACTIVE_WINDOW.  Trying to work around...
Oct 28 20:18:00 server org.gnome.Shell.desktop[2053]: Window manager warning: W1 appears to be one of the offending windows with a timestamp of 9093426.  Working around...
[tcarrigan@server my_articles]$ 

10. cola -f archivo

La -f variante de la cola El comando es una versión completamente diferente del comando original. Esta bandera permite al usuario ver el archivo a medida que se escribe. Esto es increíblemente útil para solucionar problemas de inicio/apagado de aplicaciones y sistemas por igual.

Ahora lo sabes

Si siguió este tutorial, debería tener otros 10 comandos en el arsenal de su terminal. Desde mover, copiar, crear y actualizar hasta varias formas de leer el contenido de los archivos, debe sentirse cómodo moviéndose por el sistema de archivos y manipulando los archivos y directorios que encuentre. Si esto parece complicado, sigue practicando y serás un usuario más seguro en poco tiempo. Para obtener más consejos, trucos y herramientas, vuelva a consultarnos y habilite Sysadmin.

[ Descargar ahora:una guía para administradores de sistemas sobre secuencias de comandos Bash. ] 


Linux
  1. 5 razones para usar Linux en 2020

  2. Hoja de trucos para los comandos comunes de Linux

  3. 8 comandos de Linux para una gestión de procesos eficaz

  4. 20 comandos básicos de Linux para principiantes explicados con ejemplos

  5. 10 comandos de Linux para diagnóstico de red

Tutorial del comando lsof de Linux para principiantes (15 ejemplos)

8 comandos fundamentales de administración de archivos de Linux para nuevos usuarios

Comandos básicos de Linux para principiantes

Los 40 comandos útiles del servidor Linux para principiantes y profesionales

40 comandos git útiles para administradores y desarrolladores de Linux

Los 17 mejores comandos de solución de problemas y redes de Linux para principiantes