Como alinhar entradas de fstab facilmente

6

Editar / etc / fstab com meu editor de texto faz com que todo o espaçamento fique fora de alinhamento. Eu poderia percorrer o arquivo e inserir / excluir espaços para alinhar tudo, mas estou procurando uma solução mais automatizada. Idealmente, haveria uma página de javascript on-line em que eu poderia colocar meu fstab, e tê-lo "bastante" alinhar tudo. Então eu poderia copiar / colar o resultado final de volta no arquivo.

Existe uma solução semelhante ou melhor para esta disponível?

EDIT:
Eu uso o Linux na minha área de trabalho, e não estou procurando juntar-me à religião do vi ou do emacs apenas para editar meu fstab. O Emacs pode ser uma solução melhor para algumas pessoas, mas para algumas outras pessoas não é uma solução melhor.

EDIT2:
Aqui está um trecho de exemplo do meu fstab usando as guias. As colunas não estão alinhadas.

proc    /proc   proc    nodev,noexec,nosuid 0   0
/dev/disk/by-label/Linux    /   ext4    errors=remount-ro   0   1
/dev/disk/by-label/Home /home   ext4    defaults    0   0

Eu quero que seja automaticamente formatado com espaços e se pareça com o seguinte.

proc                        /proc   proc    nodev,noexec,nosuid 0   0
/dev/disk/by-label/Linux    /       ext4    errors=remount-ro   0   1
/dev/disk/by-label/Home     /home   ext4    defaults            0   0
    
por Sepero 14.10.2013 / 22:21

5 respostas

6

Eu gosto de usar o comando column com a opção -t para alinhar colunas em uma boa tabela:

column -t /etc/fstab
proc                      /proc  proc  nodev,noexec,nosuid  0  0
/dev/disk/by-label/Linux  /      ext4  errors=remount-ro    0  1
/dev/disk/by-label/Home   /home  ext4  defaults             0  0
    
por 15.10.2013 / 00:48
2
#!/bin/bash
# usage: fstabalign [FILE]

# This script will output fstab or other file as column aligned.
# It will not alter blank lines or #hash comments.

if [ -z "$1" ]; then
    FILE=$(cat /etc/fstab)
else
    FILE=$(cat "$1")
fi

# Separate the file contents into aligned and unaligned parts.
OUT_ALIGNED=$(echo "$FILE" | sed 's/^\s*#.*//' | nl -ba | column -t)
OUT_UNALIGNED=$(echo "$FILE" | sed 's/^\s*[^#].*//' $src | nl -ba)

# Remerge aligned and unaligned parts.
while read; do
    line_aligned="$REPLY"
    read -u 3; line_unaligned="$REPLY"
    line_aligned=$(  echo "$line_aligned"   | sed 's/\s*[0-9]*\s*//')
    line_unaligned=$(echo "$line_unaligned" | sed 's/\s*[0-9]*\s*//')
    echo "$line_aligned$line_unaligned"
done < <(echo "$OUT_ALIGNED") 3< <(echo "$OUT_UNALIGNED")
    
por 15.10.2013 / 20:11
1

EDITAR:

Ah, não notei sua edição não Vim até agora.

Uma alternativa poderia ser colocar algo assim em um script.

É assim:

  1. Extraia apenas as entradas, mantenha as linhas vazias onde os comentários estão.
  2. Envie para column e use -e para manter as linhas vazias, salve no arquivo temporário 1.
  3. Extraia comentários, salve no arquivo temporário 2.
  4. Mesclar arquivos usando paste com -d'chmod +x script_file' para descartar espaços no início.

Salve no arquivo, ./script_file e execute como fstab . Opcionalmente, especifique o arquivo ./script_file /path/to/fstab/file por ./script_file > /etc/fstab .

parece OK? Então :FmtFstab

#!/bin/bash

src="/etc/fstab"

[[ "$1" ]] && src="$1"

[[ -r "$src" ]]  || exit 1
tmp1="$(mktemp)" || exit 1
tmp2="$(mktemp)" || exit 1

# Filter out comments and pipe them through column with -e
# Save to tmp1
sed 's/^[ \t]*#.*//' "$src" | column -et > "$tmp1"

# Filter out tab lines and save to tmp2
sed 's/^[ \t]*[^#].*//' "$src" > "$tmp2"

# merge
paste -d'
:so file_name.vim
' "$tmp1" "$tmp2" rm "$tmp1" "$tmp2"

Vim:

Você pode usar um script Vim. Esta é uma reescrita de uma coisa semelhante ...

  • Adiciona um novo comando #=
  • As linhas de comentário que começam com mágica #= também são formatadas. (Assim, se você comentar uma linha fstab e quiser formatá-la, use #= no início da linha. Não espaços após :FmtFstab e entrada!).

Adicione a um arquivo de script carregado, ou carregue-o manualmente por

" Split string by pattern
" Return array/List in form : [ length, [len_match1, len_match2, ...] ]
fun! s:StrSplit2Widths(line, pat)
    let lst=split(a:line, a:pat)
    call map(lst, 'strlen(v:val)')
    return [len(lst), lst]
endfun

" Generate a string based on a "widths" list
" @widths: widths to use for each entry in list (format as from
"          s:StrSplit2Widths)
" @lst   : list with text to be printed according to widths
fun! s:WidthFmtList(widths, lst)
    let i = len(a:lst) - 1
    let lif=""
    while i >= 0
        let lif = printf("%-*s", a:widths[1][i], a:lst[i]) . " " . lif
        let i = i - 1
    endwhile
    return lif
endfun

" Format current line according to widths
fun! s:FmtBufLine(widths)
    let lst=split(getline("."), '\s\+')
    if a:widths[0] != len(lst)
        return
    endif

    let lif = s:WidthFmtList(a:widths, lst)

    call setline(line("."), lif)
endfun

fun! <SID>:FormatFstab(...)
    " Comments to include
    let incmagic = "#="
    " Header
    let hdr    = "# <file system> <mount point> <type> <options> <dump> <pass>"
    " Base widths are based on header
    let widths = s:StrSplit2Widths(hdr, '>\zs\s*\ze<')
    " Get all lines (this can be expanded to only do ranges)
    let lines  = getline(1, line("$"))

    " Remove all lines not matching pattern
    call filter(lines, 'v:val =~ "^\s*\([^#]\|' . incmagic . '\)"')

    " Calculate width for each column
    for line in lines
        let lw = s:StrSplit2Widths(line, '\s\+')
        while lw[0] < widths[0]
            call add(lw[1], 0)
            let lw[0] = lw[0] + 1
        endwhile
        call map(widths[1], 'lw[1][v:key] > v:val ? lw[1][v:key] : v:val')
    endfor

    " Format each line matching pattern
    silent exec ':g/^\s*\(' . incmagic . '\|[^#]\)/ call s:FmtBufLine(widths)'

    " Format header
    let hlst = split(hdr, '>\zs\s*\ze<')
    silent :%s/^\s*#\s*<file system>.*/\=s:WidthFmtList(widths, hlst)
endfun

" ex command
command! -nargs=0 -bar FmtFstab call <SID>:FormatFstab()

Quando o arquivo for aberto no Vim, simplesmente diga %code% e ele será formatado. Também formata o cabeçalho de acordo.

( Eu também tenho um script que insere ou lista os UUIDs se isso for de interesse. )

#!/bin/bash

src="/etc/fstab"

[[ "$1" ]] && src="$1"

[[ -r "$src" ]]  || exit 1
tmp1="$(mktemp)" || exit 1
tmp2="$(mktemp)" || exit 1

# Filter out comments and pipe them through column with -e
# Save to tmp1
sed 's/^[ \t]*#.*//' "$src" | column -et > "$tmp1"

# Filter out tab lines and save to tmp2
sed 's/^[ \t]*[^#].*//' "$src" > "$tmp2"

# merge
paste -d'
:so file_name.vim
' "$tmp1" "$tmp2" rm "$tmp1" "$tmp2"
    
por 15.10.2013 / 07:11
1

Eu realmente prefiro nenhum alinhamento (apenas um único espaço). Mas é um problema interessante. Gostaria de saber por que column não tem uma opção para isso, parece um caso de uso perfeito ...

Alinhar o fstab inteiro levaria a linhas muito longas, pelo menos no meu caso, já que tenho alguns sistemas de arquivos com opções especiais e também alguns caminhos de dispositivo muito longos, disco por id. Então escrevi um script que alinha cada seção (dividida por linhas vazias ou linhas de comentário) individualmente.

Usando ./fstab.sh /etc/fstab :

#!/bin/bash

function push() {
    buffer="$buffer"$'\n'"$1"
}

function pop() {
    if [ "$buffer" != "" ]
    then
        echo "$buffer" | column -t
        buffer=""
    fi
}

buffer=""

while read line
do
    if [ "$line" == "" -o "${line:0:1}" == "#" ]
    then
        pop
        echo "$line"
    else
        push "$line"
    fi
done < "$1"

pop

Antes:

# /etc/fstab: static file system information.
# <fs> <mountpoint> <type> <opts> <dump/pass>

# --- SPECIAL ---

none /dev/shm tmpfs nosuid,nodev,noexec,noatime 0 0
none /tmp tmpfs noatime,nosuid,nodev 0 0
none /var/tmp/portage tmpfs noatime,mode=0750,gid=portage,uid=portage 0 0

# --- INTERNAL ---

# SSD
UUID=fa15678f-7e7e-4a47-8ed2-7cea7a5d037d / xfs noatime 0 0
UUID=529cc283-53bc-4acc-a4d3-f35278d3f2f9 /home xfs noatime 0 0

# HDD
UUID=d7562145-654c-48bb-b8d2-1552a69186f5 /home/TV xfs noatime 0 0
UUID=952b5dee-8d2a-40b2-85f9-5e5092bc1e75 /home/steam xfs noatime 0 0
UUID=4dcb18c3-f3a5-4b03-8877-063c5cd836e4 /home/jn xfs noatime 0 0
UUID=c735614a-f5f3-4232-911f-8a17cb033521 /var/www xfs noatime 0 0
/dev/HDD/windows7 /mnt/windows7 ntfs-3g offset=105906176,noauto,noatime 0 0

# HDD (OLD)
UUID=23deb461-bab5-45b7-9dca-9c2c4cdb4f50 /mnt/HDD/OLD-home xfs noauto,noatime 0 0
UUID=dd1e1eef-b548-4c94-8ebe-99dd7a648cb0 /mnt/HDD/OLD-music xfs noauto,noatime 0 0
UUID=2ae11a11-db04-4d27-a79e-d9b07dd19650 /mnt/HDD/OLD-opt xfs noauto,noatime 0 0
UUID=2abb2a27-2183-488e-8c24-e195ab3dcb5d /mnt/HDD/OLD-portage xfs noauto,noatime 0 0
UUID=3d0030f0-92da-4e66-8e60-369dfc586df7 /mnt/HDD/OLD-portage_tmp xfs noauto,noatime 0 0
UUID=89200c49-2fc2-45ed-81c8-e244b95db7ce /mnt/HDD/OLD-root xfs noauto,noatime 0 0
UUID=caebfb75-6a1c-4ed6-ad2f-d84d80221dc3 /mnt/HDD/OLD-schrott xfs noauto,noatime 0 0
UUID=cabddcee-cf07-4526-b3a3-9270edc9d171 /mnt/HDD/OLD-src xfs noauto,noatime 0 0
UUID=a2e4df4e-8c6d-4217-8889-6f483e872190 /mnt/HDD/OLD-tmp xfs noauto,noatime 0 0
UUID=4dd484f6-4142-45b3-b504-48625de1ab5c /mnt/HDD/OLD-var xfs noauto,noatime 0 0

# ODD
/dev/sr0 /mnt/cdrom auto user,noauto,ro 0 0

# --- EXTERNAL ---

# USB-Boot-Stick
LABEL="boot_key" /boot ext2 noauto,noatime 0 0
LABEL="boot_dos" /mnt/boot/dos vfat noauto,noatime 0 0
LABEL="boot_iso" /mnt/boot/iso ext2 noauto,noatime 0 0
LABEL="live0" /mnt/boot/live0 ext2 noauto,noatime 0 0
LABEL="live1" /mnt/boot/live1 ext2 noauto,noatime 0 0

# iriver Story HD
/dev/disk/by-id/usb-iriver_Story_EB07_3230204E6F76-0:0 /mnt/iriver/knv auto user,noauto,noatime 0 0
/dev/disk/by-id/usb-iriver_Story_SD_3230204E6F76-0:1 /mnt/iriver/ext auto user,noauto,noatime 0 0

# Sandisk Sansa CLIP
UUID=C65F-1E04 /mnt/mp3 auto user,noauto,noatime 0 0

# Eltern-Fernseher
UUID=115BF67A31CB6C02 /mnt/wdtv ntfs-3g locale=en_US.utf8,user,noauto 0 0
UUID=D27A-7C74 /mnt/pvr vfat user,noauto,noatime 0 0

Depois:

# /etc/fstab: static file system information.
# <fs> <mountpoint> <type> <opts> <dump/pass>

# --- SPECIAL ---

none  /dev/shm          tmpfs  nosuid,nodev,noexec,noatime                0  0
none  /tmp              tmpfs  noatime,nosuid,nodev                       0  0
none  /var/tmp/portage  tmpfs  noatime,mode=0750,gid=portage,uid=portage  0  0

# --- INTERNAL ---

# SSD
UUID=fa15678f-7e7e-4a47-8ed2-7cea7a5d037d  /      xfs  noatime  0  0
UUID=529cc283-53bc-4acc-a4d3-f35278d3f2f9  /home  xfs  noatime  0  0

# HDD
UUID=d7562145-654c-48bb-b8d2-1552a69186f5  /home/TV       xfs      noatime                          0  0
UUID=952b5dee-8d2a-40b2-85f9-5e5092bc1e75  /home/steam    xfs      noatime                          0  0
UUID=4dcb18c3-f3a5-4b03-8877-063c5cd836e4  /home/jn       xfs      noatime                          0  0
UUID=c735614a-f5f3-4232-911f-8a17cb033521  /var/www       xfs      noatime                          0  0
/dev/HDD/windows7                          /mnt/windows7  ntfs-3g  offset=105906176,noauto,noatime  0  0

# HDD (OLD)
UUID=23deb461-bab5-45b7-9dca-9c2c4cdb4f50  /mnt/HDD/OLD-home         xfs  noauto,noatime  0  0
UUID=dd1e1eef-b548-4c94-8ebe-99dd7a648cb0  /mnt/HDD/OLD-music        xfs  noauto,noatime  0  0
UUID=2ae11a11-db04-4d27-a79e-d9b07dd19650  /mnt/HDD/OLD-opt          xfs  noauto,noatime  0  0
UUID=2abb2a27-2183-488e-8c24-e195ab3dcb5d  /mnt/HDD/OLD-portage      xfs  noauto,noatime  0  0
UUID=3d0030f0-92da-4e66-8e60-369dfc586df7  /mnt/HDD/OLD-portage_tmp  xfs  noauto,noatime  0  0
UUID=89200c49-2fc2-45ed-81c8-e244b95db7ce  /mnt/HDD/OLD-root         xfs  noauto,noatime  0  0
UUID=caebfb75-6a1c-4ed6-ad2f-d84d80221dc3  /mnt/HDD/OLD-schrott      xfs  noauto,noatime  0  0
UUID=cabddcee-cf07-4526-b3a3-9270edc9d171  /mnt/HDD/OLD-src          xfs  noauto,noatime  0  0
UUID=a2e4df4e-8c6d-4217-8889-6f483e872190  /mnt/HDD/OLD-tmp          xfs  noauto,noatime  0  0
UUID=4dd484f6-4142-45b3-b504-48625de1ab5c  /mnt/HDD/OLD-var          xfs  noauto,noatime  0  0

# ODD
/dev/sr0  /mnt/cdrom  auto  user,noauto,ro  0  0

# --- EXTERNAL ---

# USB-Boot-Stick
LABEL="boot_key"  /boot            ext2  noauto,noatime  0  0
LABEL="boot_dos"  /mnt/boot/dos    vfat  noauto,noatime  0  0
LABEL="boot_iso"  /mnt/boot/iso    ext2  noauto,noatime  0  0
LABEL="live0"     /mnt/boot/live0  ext2  noauto,noatime  0  0
LABEL="live1"     /mnt/boot/live1  ext2  noauto,noatime  0  0

# iriver Story HD
/dev/disk/by-id/usb-iriver_Story_EB07_3230204E6F76-0:0  /mnt/iriver/knv  auto  user,noauto,noatime  0  0
/dev/disk/by-id/usb-iriver_Story_SD_3230204E6F76-0:1    /mnt/iriver/ext  auto  user,noauto,noatime  0  0

# Sandisk Sansa CLIP
UUID=C65F-1E04  /mnt/mp3  auto  user,noauto,noatime  0  0

# Eltern-Fernseher
UUID=115BF67A31CB6C02  /mnt/wdtv  ntfs-3g  locale=en_US.utf8,user,noauto  0  0
UUID=D27A-7C74         /mnt/pvr   vfat     user,noauto,noatime            0  0
    
por 15.10.2013 / 18:26
0

O vim deve funcionar ou emacs. Até mesmo o nano deve exibir o fstab corretamente. Se você estiver querendo usar uma GUI do editor de texto, você pode tentar o gedit. Se você realmente quer colocar seu fstab em um editor online, então você pode usar o google docs (e depois copiar e colar).

Certifique-se de estar usando guias para espaçar seu fstab e não espaços únicos. Isso pode causar inconsistências, especialmente se você estiver usando um pouco de ambos.

É possível que pareça desagradável porque a janela do shell não é grande o suficiente para caber no texto inteiro na linha.

    
por 14.10.2013 / 23:30