как читать строку с завершающим нулем из двоичного файла

Как предложил @fiximan, я попытался проверить, существует ли сеанс tmux или нет, а затем выполнить некоторый код и, наконец, с небольшой настройкой мне удалось получить нужный макет. Вот что я добавил в свой .bashrc :

test -z "$TMUX" && (tmux new-session -d && tmux split-window -h && tmux split-window -v && tmux -2 attach-session -d)

Я разобью приведенное выше для объяснения:

  1. test -z "$ TMUX" -> Это проверяет, существует уже запущенный сеанс tmux или нет, таким образом предотвращая вложение сеансов tmux
  2. tmux new-session -d -> Создает новый сеанс
  3. tmux split-window -h -> Разбивает окно по вертикали
  4. tmux split-window -v -> Разделяет окно по горизонтали
  5. tmux -2 attach-session -d -> Присоединяет сеансы

ПРИМЕЧАНИЕ. - Я использовал оператор && , а не оператор || , потому что в последнем случае произойдет короткое замыкание.

1
16.05.2018, 19:38
1 ответ

Solución 1 :Asignación directa de variables

Si todo lo que le preocupa son los bytes nulos, entonces debería poder leer directamente los datos del archivo en una variable utilizando el método estándar que prefiera, es decir, debería poder simplemente ignorar los bytes nulos y leer los datos del archivo. Aquí hay un ejemplo usando el comando caty la sustitución de comando:

$ data="$(cat eeprom)"
$ echo "${data}"
MAC_ADDRESS=12:34:56:78:90,PCB_MAIN_ID=m/SF-1V/MAIN/0.0,PCB_PIGGY1_ID=n/SF-1V/PS/0.0,CSL_HW_VARIANT=D

Esto funcionó para mí dentro de un contenedor BusyBox Docker.

Solución 2 :Usando xxdy un bucle for

Si desea tener más control, puede usar xxdpara convertir los bytes en cadenas hexadecimales e iterar sobre estas cadenas. Luego, mientras itera sobre estas cadenas, puede aplicar la lógica que desee, p. podría omitir explícitamente los valores nulos iniciales e imprimir el resto de los datos hasta que alcance alguna condición de interrupción.

Aquí hay un script que especifica una "lista blanca -" de caracteres válidos (ASCII 32 a 127 ), trata cualquier subsecuencia de otros caracteres como un separador y extrae todas las subcadenas válidas:

#!/bin/sh
# get_hex_substrings.sh

# Get the path to the data-file as a command-line argument
datafile="$1"

# Keep track of state using environment variables
inside_padding_block="true"
inside_bad_block="false"

# NOTE: The '-p' flag is for "plain" output (no additional formatting)
# and the '-c 1' option specifies that the representation of each byte
# will be printed on a separate line
for h in $(xxd -p -c 1 "${datafile}"); do

    # Convert the hex character to standard decimal
    d="$((0x${h}))"

    # Case where we're still inside the initial padding block
    if [ "${inside_padding_block}" == "true" ]; then
        if [ "${d}" -ge 32 ] && [ "${d}" -le 127 ]; then
            inside_padding_block="false";
            printf '\x'"${h}";
        fi

    # Case where we're passed the initial padding, but inside another
    # block of non-printable characters
    elif [ "${inside_bad_block}" == "true" ]; then
        if [ "${d}" -ge 32 ] && [ "${d}" -le 127 ]; then
            inside_bad_block="false";
            printf '\x'"${h}";
        fi

    # Case where we're inside of a substring that we want to extract
    else
        if [ "${d}" -ge 32 ] && [ "${d}" -le 127 ]; then
            printf '\x'"${h}";
        else
            inside_bad_block="true";
            echo
        fi
    fi
done

if [ "${inside_bad_block}" == "false" ]; then
    echo
fi

Ahora podemos probar esto creando un archivo de ejemplo que tiene subsecuencias \x00y \xffque separan subcadenas:

printf '\x00\x00\x00string1\xff\xff\xffstring2\x00\x00\x00string3\x00\x00\x00' > data.hex

Y aquí está el resultado que obtenemos al ejecutar el script:

$ sh get_hex_substrings.sh data.hex
string1
string2
string3

Solución 3 :Usando los comandos try cut

También puede intentar usar los comandos try cutpara lidiar con los bytes nulos. Aquí hay un ejemplo de extracción de la primera cadena terminada en nulo -de una lista de cadenas terminadas en nulo -comprimiendo/contrayendo caracteres nulos adyacentes -y convirtiéndolos en líneas nuevas:

$ printf '\000\000\000string1\000\000\000string2\000\000\000string3\000\000\000' > file.dat
$ tr -s '\000' '\n' < file.dat | cut -d$'\n' -f2
string1
1
27.01.2020, 23:43

Теги

Похожие вопросы