Categorías
shell

Día 03 Avanzada gestión de archivos Linux

Día 03 Avanzada gestión de archivos Linux

1. Procesamiento de texto Tres Mosqueteros Comando

Los comandos de los Tres Mosqueteros se explicarán en profundidad en la programación de conchas, aquí aprendemos el uso más básico

1.sed

Editor de streaming, principalmente bueno en la edición de archivos, podemos personalizar las instrucciones para editar archivos de antemano, y luego dejar sed completar automáticamente la edición general de los archivos

1.1 Uso

sed option'location + command' file path

1.2 Opciones

  • -n cancelar la salida predeterminada

    sed -n '1p;2p;4p' 1.txt # With n only print the required part
    ---------------------------------
    user12312
    23123user
    111asda2323
    
    sed '1p;2p;4p' 1.txt  # Additional output based on the default output
    ---------------------------------
    user12312
    user12312
    23123user
    23123user
    1123user12323
    111asda2323
    111asda2323
    2131asdasd23423asdas35454dxcz
    00000user9999user8888user
    
  • -r soporta metacaracters regulares extendidos (porque el regular aún no se aprende, así que lo entenderé aquí por el momento)

  • -i editar el archivo inmediatamente

1.3 Posicionamiento

Posicionamiento de filas

  1. Posición a la primera línea
  2. 1,3 representa desde la primera fila hasta la tercera fila
  3. No escribir posicionamiento significa posicionar todas las filas

Segmentación por expresiones regulares

  1. /user/ ContienenuserLínea de
  2. /^user/ParauserEl principio de la línea
  3. /user$/ParauserLínea final

Número + posicionamiento de expresiones regulares

  1. 1, 8p Representa la impresión de 1 a 8 líneas

    sed -n '1,7p' 1.txt # The text is only 6 lines
    ----------------------------------
    user12312
    23123user
    1123user12323
    111asda2323
    2131asdasd23423asdas35454dxcz
    00000user9999user8888user
    
  2. 1, /user/pSignifica tomar desde la primera línea hasta el primer partido para/user/Línea de

    sed -n '1, /231/p' 1.txt   # Print 1 to lines starting with 231
    ----------------------------------
    user12312
    23123user
    

1.4 Comando

  • d eliminar

    sed '1d;2d;5d' 1.txt 
    -----------------------------------
    1123user12323
    111asda2323
    00000user9999user8888user
    
    sed '1,4d' 1.txt  # Delete 1-4 so there are only 5 and 6 left
    -----------------------------------
    2131asdasd23423asdas35454dxcz
    00000user9999user8888user
    
  • p número de filas

    sed -n '1p;2p;4p' 1.txt 
    ------------------------------------
    user12312
    23123user
    111asda2323
    
    sed -n '1, /8user$/p' 1.txt   # Output the first line to the content ending with 8user
    ------------------------------------
    user12312
    23123user
    1123user12323
    111asda2323
    2131asdasd23423asdas35454dxcz
    00000user9999user8888user
    
  • s///g

    sed 's/user/SuperUser/g' 1.txt  # Replace the user in all lines with SuperUser g is a statement equivalent to global. Change all the lines without adding only one of the lines.
    ----------------------------------
    SuperUser12312
    23123SuperUser
    1123SuperUser12323
    111asda2323
    2131asdasd23423asdas35454dxcz
    00000SuperUser9999SuperUser8888SuperUser
    
    sed 's/user/SuperUser/' 1.txt   # No g
    --------------------------------
    SuperUser12312
    23123SuperUser
    1123SuperUser12323
    111asda2323
    2131asdasd23423asdas35454dxcz
    00000SuperUser9999user8888user
    
    sed 's/^user/SuperHero/g' 1.txt  # The user in the line starting with user is replaced by SuperHero
    -------------------------------
    SuperHero12312
    23123user
    1123user12323
    111asda2323
    2131asdasd23423asdas35454dxcz
    00000user9999user8888user
    
    sed '1, 4s/user/Waibi/g' 1.txt   # Replace line 1-4 user with waibi
    ------------------------------
    Waibi12312
    23123Waibi
    1123Waibi12323
    111asda2323
    2131asdasd23423asdas35454dxcz
    00000user9999user8888user
    
    
    # Add the -i option, modify the file directly, usually after debugging to ensure that there is no problem, add the -i option
    sed '1, 4s/user/Waibi/g' 1.txt -i
    cat 1.txt 
    ------------------------------
    Waibi12312
    23123Waibi
    1123Waibi12323
    111asda2323
    2131asdasd23423asdas35454dxcz
    00000user9999user8888user
    

    El comando se puede utilizar; número para conectar muchos, como 1d; 3d; 5d significa eliminar 1, 3, 5 líneas

2.awk

awk se utiliza principalmente para procesar texto con formato, como/etc/passwdEsto, de hecho, awk es un lenguaje de programación que puede completar operaciones muy potentes de forma independiente, vamos a introducir en detalle en la programación shell

1.1 Uso

awk option'pattern{action}' file path

1.2 Opciones

-F especifica el separador de líneas

1.3 Proceso de trabajo

awk -F: '{print $1,$3}' /etc/passwd

  • Awk leerá una línea del archivo y lo asignará a $0
  • A continuación, awk dividirá la línea en n segmentos con el separador especificado por -F,Máspuede llegar a100 segmentos, Dar $1 al primer párrafo, $2 al segundo párrafo, y así sucesivamente
  • imprimir genera el primer y tercer párrafos de la línea, la coma representa el separador de salida, el valor predeterminado es el mismo que -F
  • Repita los pasos 1, 2, 3 hasta que se lea el contenido del archivo

1.4 Variables incorporadas

$0 Toda una línea de contenido

NR Número de registro, equivalente al número de línea

NF Número de segmentos separados por separado -F

1.5pattern puede ser

  • /Regular/

    /Regular/ # El contenido de la línea coincide con éxito, regular

$1 ~ /regular/ # The first paragraph of content matches the regular 
$1 !~ /regular/ # The first paragraph of content does not match the regular
  • Operación de comparación:
  NR >= 3 && NR <=5 # 3 to 5 lines
$1 == "root" # The first paragraph is equal to root

1.6 la acción puede ser

imprimir $1,$3

1.7 Uso

cat 2.txt  # Edited text
---------------------------------
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin


3.grep

1.1 Uso

grep option'regular' file path

1.2 Opciones

  • -n, –line-number agregue su número de línea relativo en el archivo antes de cada línea filtrada
  • -i, –ignore-case ignore case
  • –Color de color
  • -l, –files-with-matches Si la coincidencia se realiza correctamente, solo se imprimirá el nombre de archivo y, si falla, no se imprimirá. Por lo general -rl se utiliza juntos, grep -rl ‘raíz’ /etc
  • -R, -r, –recursividad recursiva

1.3 Ejemplo

grep '^root' /etc/passwd  # Filter the files starting with root under the /etc/passwd file
-------------------------------
root:x:0:0:root:/root:/bin/bash

grep -n '^root' /etc/passwd  # Filter the files starting with root under the /etc/passwd file
-------------------------------
1:root:x:0:0:root:/root:/bin/bash  # Rows

grep -n 'bash$' /etc/passwd  # Filter files with bashjiewei under the /etc/passwd file
-------------------------------
1:root:x:0:0:root:/root:/bin/bash

grep -rl '^root' /etc  # Match the files in the etc folder that start with root. If the match is successful, it will be printed out if it is unsuccessful and not printed


# grep also supports pipes, we can find that the Three Musketeers commands all support pipes
[[email protected] ~]# ps aux |grep ssh
root 968 0.0 0.2 112908 4312 ? Ss 14:05 0:00 /usr/sbin/sshd
-D
root 1305 0.0 0.3 163604 6096 ? Ss 14:05 0:00 sshd:
[email protected]/0
root 1406 0.0 0.3 163600 6240 ? Ss 14:05 0:00 sshd:
[email protected]/1
root 2308 0.0 0.0 112724 984 pts/1 R+ 15:30 0:00 grep --
color=auto ssh
[[email protected] ~]# ps aux |grep [s]sh
root 968 0.0 0.2 112908 4312 ? Ss 14:05 0:00 /usr/sbin/sshd
-D
root 1305 0.0 0.3 163604 6096 ? Ss 14:05 0:00 sshd:
[email protected]/0
root 1406 0.0 0.3 163600 6240 ? Ss 14:05 0:00 sshd:
[email protected]/1

Dos, búsqueda de archivos de administración de archivos

1. Vea el archivo al que pertenece el comando

[[email protected] home]# which ip
/usr/sbin/ip
[[email protected] home]# whereis ip
ip: /usr/sbin/ip /usr/share/man/man8/ip.8.gz

2. Encontrar archivos

find [options] [path...] [expression]

Por nombre de archivo

[[email protected] ~]# find /etc -name "ifcfg-eth0"
[[email protected] ~]# find /etc -iname "ifcfg-eth0" # -i ignore case
[[email protected] ~]# find /etc -iname "ifcfg-eth*"

Por tamaño de archivo

[[email protected] ~]# find /etc -size +3M # greater than 3M
[[email protected] ~]# find /etc -size 3M
[[email protected] ~]# find /etc -size -3M
[[email protected] ~]# find /etc -size +3M -ls # -ls found processing action

Especifique la profundidad del directorio de búsqueda:

-maxdepth levels
[[email protected] ~]# find / -maxdepth 5 -a -name "ifcfg-eth0" # -a and, -o or,
 Without -a, the default is -a

Buscar por tiempo (atime, mtime, ctime):

Básicamente no hay diferencia en esto, porque no lo modificamos

[[email protected] ~]# find /etc -mtime +3 # The modification time exceeds 3 days
[[email protected] ~]# find /etc -mtime 3 # The modification time is equal to 3 days
[[email protected] ~]# find /etc -mtime -3 # The modification time is within 3 days

Buscar por propietario de archivos y grupo:

[[email protected] ~]# find /home -user egon # The file whose owner is egon
[[email protected] ~]# find /home -group it # The belonging group is the file of the it group
[[email protected] ~]# find /home -user egon -group it
[[email protected] ~]# find /home -user egon -a -group it # Same meaning as above
[[email protected] ~]# find /home -user egon -o -group it
[[email protected] ~]# find /home -nouser # The user still exists, and the record is deleted in /etc/passwd
[[email protected] ~]# find /home -nogroup # The user still exists, and the record is deleted in /etc/group
[[email protected] ~]# find /home -nouser -o -nogroup

Por tipo de archivo:

[[email protected] ~]# find /dev -type f # fnormal
[[email protected] ~]# find /dev -type d # d directory
[[email protected] ~]# find /dev -type l # l link
[[email protected] ~]# find /dev -type b # b block device
[[email protected] ~]# find /dev -type c # c character device
[[email protected] ~]# find /dev -type s # s socket
[[email protected] ~]# find /dev -type p # p pipeline file

Encontrar según el número de inode: -inum n

[[email protected] ~]# find / -inum 1811

Por permisos de archivo

[[email protected] ~]# find . -perm 644 -ls
[[email protected] ~]# find . -perm -644 -ls
[[email protected] ~]# find . -perm -600 -ls
[[email protected] ~]# find /sbin -perm -4000 -ls # contains set uid
[[email protected] ~]# find /sbin -perm -2000 -ls # contains set gid
[[email protected] ~]# find /sbin -perm -1000 -ls # contains sticky

Busque la acción posterior al procesamiento:

-print
-ls
-delete
-exec
-ok
[[email protected] ~]# find /etc -name "ifcfg*" -print # quotes must be added
[[email protected] ~]# find /etc -name "ifcfg*" -ls
[[email protected] ~]# find /etc -name "ifcfg*" -exec cp -rvf {} /tmp ; # non-interactive
[[email protected] ~]# find /etc -name "ifcfg*" -ok cp -rvf {} /tmp ; # Interactive each must be yes or y
[[email protected] ~]# find /etc -name "ifcfg*" -exec rm -rf {} ;
[[email protected] ~]# find /etc -name "ifcfg*" -delete # Same as above

3. Carga y descarga de archivos

1. Descargar

wget comando

wget  -O local path remote package link address # Download the remote package to the local, -O specifies where to download, you can create a path -O local path
# ps: If the wget download prompts that the SSL connection cannot be established, add the option --no-check-certificate
wget  --no-check-certificate -O local path remote package link address

comando curl

The #curl command is a file transfer tool that uses URL rules to work on the command line. It supports file upload and download, so it is a comprehensive transmission tool, but according to tradition, it is customary to call curl as a download tool. As a powerful tool, curl supports many protocols including HTTP, HTTPS, [ftp], etc. It also supports POST, cookies, authentication, downloading some files from a specified offset, user agent string, speed limit, file size, progress bar And other features. To automate web processing flow and data retrieval, curl can help.


[[email protected] ~]# curl -o 123.png https://www.xxx.com/img/hello.png
# ps: If you are unable to resume the SSL link when you encounter the download prompt, use the -k option or --insecure

curl -k -o name.jpg https://www.bing.com/th?id=OHR.BernCH_ZH-CN0890742909_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=HpEdgeAn

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-dEeFs3BR-1606126022318)(https://i.loli.net/2020/11/23/9qFoasYSEmQjcLi.png )]

sz comando Este comando requiere que lrzsz se instale

El sistema no tiene este comando de forma predeterminada, es necesario descargar: yum instalar lrzsz -y # Descargar / enviar el archivo seleccionado en el servidor a la máquina

2 Subir

El comando rz no está disponible de forma predeterminada y debe instalarse

# The system does not have this command by default, it needs to be downloaded: yum install lrzsz -y
# Run this command will pop up a file selection window, select the file from the local and upload it to the server.
[[email protected] opt]# rz # If the file is already saved, the upload fails, you can use the -E option to solve
[[email protected] opt]# rz -E # -E If the target file name already exists, rename the incoming file. The new file name will add one
 Dots and a number(0..999)

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-SjBUIXCp-1606126022322)(https://i.loli.net/2020/11/23/V4LzBTuXAECFIHc.png )]

Gestión de cuatro archivos: entrada y redirección

Gestión de cinco archivos: comandos de procesamiento de caracteres

Comando 1.sort

Se utiliza para ordenar el contenido del archivo

  • -n # Ordenar por valor
  • -r # Ordenar en orden inverso
  • -k # Ordenar por una columna
  • -t # Especifique el separador, el valor predeterminado es utilizar un espacio como separador

Prepare el archivo y escriba una sección de contenido innecesario

cat >> test.txt  <<GG  # Open the test.txt file and write additional (>>) content when GG appears, end the write
> b:3
> c:2
> a:4
> e:5
> d:1
> f:11
> GG

Clasificación básica

sort test.txt  # The default is the first sorted case-insensitive
---------------------------
a:4
b:3
c:2
d:1
e:5
f:11
Z:77

sort test.txt -r  # Reverse order == sort -r test.txt
Z:77
f:11
e:5
d:1
c:2
b:3
a:4

Elija ordenar el contenido

sort -t ':' -n -k2 test.txt  # Separate by':' (-t) Use the second (k2) number (-n) element after separation to sort forward
-------------------------------------
d:1
c:2
b:3
a:4
e:5
f:11
Z:77

# Reverse order is the same

Comando 2.uniq único

Se utiliza para comprobar y eliminar filas y columnas repetidas en archivos de texto, generalmente utilizados junto con el comando sort

  • -c # Mostrar el número de recurrencias de la fila junto a cada columna.
  • -d # Sólo mostrar las filas y columnas repetidas.
  • -u # Sólo mostrar los rangos una vez.

Prepare el archivo y escriba un fragmento de contenido desordenado

cat >> 2.txt <<GG
> hello
> 123
> hello
> 123
> func
> gg
> GG

Uso básico

sort 2.txt 
-----------------------------
123
123
func
gg
hello
hello

sort 2.txt |uniq   # Do not repeat sorting
----------------------------
123
func
gg
hello

-c número de recuento de uso

sort 2.txt | uniq -c  # Do not repeat sorting and display the number of occurrences
---------------------------
      2 123
      1 func
      1 gg
      2 hello

¿El uso de -d aparece varias veces? ¿Dúo?

sort 2.txt | uniq -d
--------------------------
123
hello

El uso de -u único aparece una vez

sort 2.txt | uniq -u
-------------------------
func
gg

Comando 3.cut

El comando cut se utiliza para mostrar la parte especificada de la línea y eliminar el campo especificado en el archivo

  • -d # Especificar el separador de campos, el separador de campo predeterminado es «TAB»;
  • -f # Mostrar el contenido del campo especificado;
head -1 /etc/passwd
------------------------------
1    2 3 4  5     6     7 
root:x:0:0:root:/root:/bin/bash

head -1 /etc/passwd | cut -d ':' -f1,2,4,6,7  # The content displayed in the previous item is separated by':' (-d) to display (-f) 1, 2, 4, 6, 7
------------------------------
root:x:0:/root:/bin/bash

Comando de 5.4 tr

Reemplazar o eliminar comandos

  • -d # eliminar caracteres
[[email protected] ~]# head -1 /etc/passwd |tr "root" "ROOT"
ROOT:x:0:0:ROOT:/ROOT:/bin/bash
[[email protected] ~]#
[[email protected] ~]# head -1 /etc/passwd |tr -d "root" # delete the root character
:x:0:0::/:/bin/bash
[[email protected] ~]# echo "hello egon qq:378533872" > a.txt
[[email protected] ~]# tr "egon" "EGON" < a.txt
hEllO EGON qq:378533872  #  egon replaced with uppercase

Comando de 5.5 wc

Estadísticas

  • -c # Contar el número de bytes del archivo;
  • -l # contar el número de líneas en el archivo;
  • -w # Contar el número de palabras en el archivo. De forma predeterminada, los caracteres en blanco se utilizan como separadores
[[email protected] ~]# ll file.txt
 -rw-r--r--. 1 root root 25 August 12 20:09 file.txt
[[email protected] ~]# wc -c file.txt
25 file.txt
[[email protected] ~]# cat file.txt
hello
123
hello
123
func
[[email protected] ~]# wc -l file.txt
5 file.txt
[[email protected] ~]# grep "hello" file.txt |wc -l
2
[[email protected] ~]# cat file.txt
hello
123
hello
123
func
[[email protected] ~]# wc -w file.txt
5 file.txt

.