AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / ubuntu / Perguntas / 1392560
Accepted
WinEunuuchs2Unix
WinEunuuchs2Unix
Asked: 2022-02-13 10:57:35 +0800 CST2022-02-13 10:57:35 +0800 CST 2022-02-13 10:57:35 +0800 CST

Como alterar a ordem de classificação `lsblk`?

  • 772

Alterar lsblkordem de classificação

lsblkclassifica as partições em uma ordem difícil de seguir. Um método de classificá-lo sem ter que escrever um script bash ou um script python seria a primeira escolha.

Uma pergunta semelhante foi feita em Unix e Linux:

  • saída lsblk não classificada

No entanto, a resposta para usar o -x NAMEparâmetro para classificação faz com que o recuo da árvore desapareça.

Ordem de classificação atual

É assim que lsblkaparece agora:

$ lsdrv

NAME         FSTYPE   LABEL            MOUNTPOINT                    SIZE MODEL
nvme0n1                                                              477G Samsung SSD 960 PRO 512GB               
├─nvme0n1p9  swap                      [SWAP]                        7.9G 
├─nvme0n1p7  ext4     Old_Ubuntu_16.04 /mnt/old                     23.1G 
├─nvme0n1p5  ntfs                                                    859M 
├─nvme0n1p3                                                           16M 
├─nvme0n1p1  ntfs                                                    450M 
├─nvme0n1p8  ntfs     Shared_WSL+Linux /mnt/e                          9G 
├─nvme0n1p10 ext4     Ubuntu_18.04     /mnt/clone                   27.2G 
├─nvme0n1p6  ext4     New_Ubuntu_16.04 /                            45.1G 
├─nvme0n1p4  ntfs     NVMe_Win10       /mnt/c                      363.2G 
└─nvme0n1p2  vfat                      /boot/efi                      99M 
mmcblk0                                                            119.1G 
└─mmcblk0p1  vfat     SANDISK128       /media/rick/SANDISK128      119.1G 
sr0                                                                 1024M DVD+/-RW DW316  
sda                                                                931.5G HGST HTS721010A9
├─sda4       ntfs     WINRETOOLS                                     450M 
├─sda2                                                               128M 
├─sda5       ntfs     Image                                         11.4G 
├─sda3       ntfs     HGST_Win10       /mnt/d                        919G 
└─sda1       vfat     ESP                                            500M 

Ordem de classificação proposta

É assim que lsblkdeve ser classificado:

$ lsdrv

NAME         FSTYPE   LABEL            MOUNTPOINT                    SIZE MODEL
nvme0n1                                                              477G Samsung SSD 960 PRO 512GB               
├─nvme0n1p1  ntfs                                                    450M 
├─nvme0n1p2  vfat                      /boot/efi                      99M 
├─nvme0n1p3                                                           16M 
├─nvme0n1p4  ntfs     NVMe_Win10       /mnt/c                      363.2G 
├─nvme0n1p5  ntfs                                                    859M 
├─nvme0n1p6  ext4     New_Ubuntu_16.04 /                            45.1G 
├─nvme0n1p7  ext4     Old_Ubuntu_16.04 /mnt/old                     23.1G 
├─nvme0n1p8  ntfs     Shared_WSL+Linux /mnt/e                          9G 
├─nvme0n1p9  swap                      [SWAP]                        7.9G 
└─nvme0n1p10 ext4     Ubuntu_18.04     /mnt/clone                   27.2G 
mmcblk0                                                            119.1G 
└─mmcblk0p1  vfat     SANDISK128       /media/rick/SANDISK128      119.1G 
sr0                                                                 1024M DVD+/-RW DW316  
sda                                                                931.5G HGST HTS721010A9
├─sda1       vfat     ESP                                            500M 
├─sda2                                                               128M 
├─sda3       ntfs     HGST_Win10       /mnt/d                        919G 
├─sda4       ntfs     WINRETOOLS                                     450M 
└─sda5       ntfs     Image                                         11.4G 

Nota: lsdrv é um alias definido em ~/.bashrc:

$ alias lsdrv

alias lsdrv='lsblk -o NAME,FSTYPE,LABEL,MOUNTPOINT,SIZE,MODEL |egrep -v "^loop"'

Resumo

As complexidades da alteração da ordem de classificação são:

  • Apenas partições com caracteres de desenho de linha ├─e └─são classificadas em suas unidades.
  • Depois de classificar as partições, a última partição pode precisar ser ├─substituída por └─.
  • Depois de classificar as partições, a primeira partição para a penúltima partição pode precisar ser └─substituída por ├─.
  • O velho "calcanhar de Aquiles" de classificar os lugares 10depois de , 1 EG 1 depois . Realmente deve aparecer antes .102 9 10

A ordem de classificação de lsblktem sido um espinho por anos. Espero que alguém tenha uma solução simples com utilitários GNU como: awk, sed, grep, uniqe/ou sort, etc.

partitioning
  • 1 1 respostas
  • 259 Views

1 respostas

  • Voted
  1. Best Answer
    WinEunuuchs2Unix
    2022-02-13T14:50:48+08:002022-02-13T14:50:48+08:00

    Acabei escrevendo uma função de classificação genérica para resolver o problema.

    Nova lsblkordem de classificação

    $ lsdrv | sblk
    
    NAME         FSTYPE   LABEL            MOUNTPOINT                    SIZE MODEL
    nvme0n1                                                              477G Samsung SSD 960 PRO 512GB               
    ├─nvme0n1p1  ntfs                                                    450M 
    ├─nvme0n1p2  vfat                      /boot/efi                      99M 
    ├─nvme0n1p3                                                           16M 
    ├─nvme0n1p4  ntfs     NVMe_Win10       /mnt/c                      363.2G 
    ├─nvme0n1p5  ntfs                                                    859M 
    ├─nvme0n1p6  ext4     New_Ubuntu_16.04 /                            45.1G 
    ├─nvme0n1p7  ext4     Old_Ubuntu_16.04 /mnt/old                     23.1G 
    ├─nvme0n1p8  ntfs     Shared_WSL+Linux /mnt/e                          9G 
    ├─nvme0n1p9  swap                      [SWAP]                        7.9G 
    └─nvme0n1p10 ext4     Ubuntu_18.04     /mnt/clone                   27.2G 
    mmcblk0                                                            119.1G 
    └─mmcblk0p1  vfat     SANDISK128       /media/rick/SANDISK128      119.1G 
    sr0                                                                 1024M DVD+/-RW DW316  
    sda                                                                931.5G HGST HTS721010A9
    ├─sda1       vfat     ESP                                            500M 
    ├─sda2                                                               128M 
    ├─sda3       ntfs     HGST_Win10       /mnt/d                        919G 
    ├─sda4       ntfs     WINRETOOLS                                     450M 
    └─sda5       ntfs     Image                                         11.4G 
    

    Script Bash para classificar a lsblksaída

    Demorou algumas horas pesquisando diferentes comandos bash para criar uma solução. O script bash, inicialmente chamado sblkde , pode ser adaptado para outras finalidades:

    #!/bin/bash
    # Ask Ubuntu: https://askubuntu.com/questions/1392560/how-to-change-lsblk-sort-order
    oIFS="$IFS"                         # Save IFS
    IFS='|'                             # Use "|" as array delimiter
    declare -a partiions=()             # Partitions array for a given drive
    
    add_part () {
        line="$1"                       # Confusing parameter $1 becomes obvious
        part=${line%% *}                # get partition name, then get number
        key=$(echo "$part" | grep -Eo '[0-9]+$')
    
        # If length of number is less than 2, prepend "0"
        if [[ "${#key}" < 2 ]]; then
            key="0$key"                 # Prepend "0" to single digit
        fi
    
        line="${line:2}"                # Strip out tree character
        partitions+=( "$key$line" )     # Old line "├─..." now array entry "99..."
    }
    
    sort_parts () {
        # Sort partitions array with sort key into new "sorted" array
        read -r -d '' -a sorted < <( 
            echo "${partitions[*]}" | tr "|" "\n" | sort | tr "\n" "|" )
        last_i=$(( ${#sorted[@]} - 1 )) # Last 0-based index in sorted array
    
        for ((i=0; i <= $last_i; i++)); do
            line="${sorted[i]}"         # Get array line at 0-based index
            line="${line:2}"            # Strip out sort key "99"
            if [[ $i -lt $last_i ]]; then
                echo "├─$line"          # Print a line that is not the last line
            else
                echo "└─$line"          # Print last line
            fi
        done
        partitions=()                   # Empty partitions array for the next drive
    }
    
    # Main Loop
    while read line
    do
        first="${line:0:2}"
        if [[ "$first" == "├─" || "$first" == "└─" ]]; then
            add_part "$line"            # Add special line to partitions array
    
            if [[ "$first" == "└─" ]]; then
                sort_parts              # Last partition. Sort and print array
            fi
        else
            echo "$line"                # Simply print a regular line
        fi
    
    done < "${1:-/dev/stdin}"           # Read from file $1 or from standard input
    
    
    IFS="$oIFS"                         # Restore old IFS
    
    • 3

relate perguntas

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Existe um comando para listar todos os usuários? Também para adicionar, excluir, modificar usuários, no terminal?

    • 9 respostas
  • Marko Smith

    Como excluir um diretório não vazio no Terminal?

    • 4 respostas
  • Marko Smith

    Como descompactar um arquivo zip do Terminal?

    • 9 respostas
  • Marko Smith

    Como instalo um arquivo .deb por meio da linha de comando?

    • 11 respostas
  • Marko Smith

    Como instalo um arquivo .tar.gz (ou .tar.bz2)?

    • 14 respostas
  • Marko Smith

    Como listar todos os pacotes instalados

    • 24 respostas
  • Martin Hope
    Flimm Como posso usar o docker sem sudo? 2014-06-07 00:17:43 +0800 CST
  • Martin Hope
    led-Zepp Como faço para salvar a saída do terminal em um arquivo? 2014-02-15 11:49:07 +0800 CST
  • Martin Hope
    ubuntu-nerd Como descompactar um arquivo zip do Terminal? 2011-12-11 20:37:54 +0800 CST
  • Martin Hope
    TheXed Como instalo um arquivo .deb por meio da linha de comando? 2011-05-07 09:40:28 +0800 CST
  • Martin Hope
    Ivan Como listar todos os pacotes instalados 2010-12-17 18:08:49 +0800 CST
  • Martin Hope
    David Barry Como determino o tamanho total de um diretório (pasta) na linha de comando? 2010-08-06 10:20:23 +0800 CST
  • Martin Hope
    jfoucher "Os seguintes pacotes foram retidos:" Por que e como resolvo isso? 2010-08-01 13:59:22 +0800 CST
  • Martin Hope
    David Ashford Como os PPAs podem ser removidos? 2010-07-30 01:09:42 +0800 CST

Hot tag

10.10 10.04 gnome networking server command-line package-management software-recommendation sound xorg

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve