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 / user-147037

RobotJohnny's questions

Martin Hope
RobotJohnny
Asked: 2018-08-01 09:26:55 +0800 CST

O intervalo de índice da matriz não permite iterar em uma nova linha no bash

  • 2

Estou trabalhando em um script bash simples que corrige um problema de nomenclatura duplicada em um retropie.

O próprio script pega qualquer nome que é mencionado mais de uma vez em um arquivo gameslist.xml e os armazena em um array para uso posterior.

Eu acabo fazendo um loop sobre essa matriz em índices assim:

pi@retropie:~ $ for game in ${game_array[@]:0:10} ; do echo $game; done

que puxa o 1º para o 10º elemento (ou seja, ${game_array[9]}), no entanto, a saída é unida a uma linha:

pi@retropie:~ $ for game in ${game_array[@]:0:10} ; do echo $game; done
R.B.I. Baseball '94 World Series Baseball '95 Mega Games 1 Bill Walsh College Football T2: The Arcade Game Sonic & Knuckles + Sonic the Hedgehog Sega Top Five Pyramid Magic Tecmo Super Baseball Super Chinese Tycoon

Mas se eu fizer um loop em todo o array, ele será gerado em novas linhas conforme o esperado:

pi@retropie:~ $ for game in ${game_array[@]}; do echo $game; done | head -10
R.B.I. Baseball '94
World Series Baseball '95
Mega Games 1
Bill Walsh College Football
T2: The Arcade Game
Sonic & Knuckles + Sonic the Hedgehog
Sega Top Five
Pyramid Magic
Tecmo Super Baseball
Super Chinese Tycoon

o separador de campo foi definido para uma nova linha e IFS='$\n'é por isso que o segundo funciona, mas não consigo descobrir por que não é com o primeiro?

aqui está o script de teste completo para o contexto:

#!/bin/bash

user_input=$1
while [ -z "$user_input" ]; do
        echo "please enter the name of the system you want to fix the game list for"
        echo "(as it is labelled in /home/pi/RetroPie/roms)"
        read -r user_input
done

ls "/home/pi/RetroPie/roms/$user_input" >/dev/null 2>&1

if  [ "$?" -ne 0 ]; then
        echo "this doesn't appear to be a system installed here. exiting."
        exit 1
fi

games_to_fix()
{
        IFS=$'\n'
        console=$1
        filepath="/opt/retropie/configs/all/emulationstation/gamelists/$console/gamelist.xml"
        game_array=($(fgrep "<name>" "$filepath" | sort | uniq -c | sort -rn | awk  '$1 > 1 {print $0}'| cut -d ">" -f 2 | cut -d "<" -f 1))
        number_to_fix=($(fgrep "<name>" "$filepath" | sort | uniq -c | sort -rn | awk  '$1 > 1 {print $1}'))
}

get_new_name()
{
        mYpath=$1
        new_name=$(echo $mYpath | cut -d ">" -f 2 | cut -d "<" -f 1 | sed -e 's/\.\///g' | sed -e 's/\.7z//g')
}

games_to_fix $user_input

IFS=$'\n'
index=0
for i in ${number_to_fix[@]}; do
        loop=1
        for game in ${game_array[@]:$index:$i}; do
        #       for ind in $(eval echo {1..$i}); do
                line_number=$(fgrep -n "<name>$game</name>"  $filepath | awk '{print $1}' | cut -d : -f 1 | sed -e "${loop}q;d")
                path_line_number=$(expr $line_number - 1 )
                path=$(sed "${path_line_number}q;d" $filepath | cut -d : -f 2)
                get_new_name "$path"
                sed -i "${line_number}s/$game/$new_name/g" $filepath
                ((loop++))
        done
        index=$(expr index + $i);
done
bash shell
  • 2 respostas
  • 644 Views

Sidebar

Stats

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

    Possível firmware ausente /lib/firmware/i915/* para o módulo i915

    • 3 respostas
  • Marko Smith

    Falha ao buscar o repositório de backports jessie

    • 4 respostas
  • Marko Smith

    Como exportar uma chave privada GPG e uma chave pública para um arquivo

    • 4 respostas
  • Marko Smith

    Como podemos executar um comando armazenado em uma variável?

    • 5 respostas
  • Marko Smith

    Como configurar o systemd-resolved e o systemd-networkd para usar o servidor DNS local para resolver domínios locais e o servidor DNS remoto para domínios remotos?

    • 3 respostas
  • Marko Smith

    apt-get update error no Kali Linux após a atualização do dist [duplicado]

    • 2 respostas
  • Marko Smith

    Como ver as últimas linhas x do log de serviço systemctl

    • 5 respostas
  • Marko Smith

    Nano - pule para o final do arquivo

    • 8 respostas
  • Marko Smith

    erro grub: você precisa carregar o kernel primeiro

    • 4 respostas
  • Marko Smith

    Como baixar o pacote não instalá-lo com o comando apt-get?

    • 7 respostas
  • Martin Hope
    user12345 Falha ao buscar o repositório de backports jessie 2019-03-27 04:39:28 +0800 CST
  • Martin Hope
    Carl Por que a maioria dos exemplos do systemd contém WantedBy=multi-user.target? 2019-03-15 11:49:25 +0800 CST
  • Martin Hope
    rocky Como exportar uma chave privada GPG e uma chave pública para um arquivo 2018-11-16 05:36:15 +0800 CST
  • Martin Hope
    Evan Carroll status systemctl mostra: "Estado: degradado" 2018-06-03 18:48:17 +0800 CST
  • Martin Hope
    Tim Como podemos executar um comando armazenado em uma variável? 2018-05-21 04:46:29 +0800 CST
  • Martin Hope
    Ankur S Por que /dev/null é um arquivo? Por que sua função não é implementada como um programa simples? 2018-04-17 07:28:04 +0800 CST
  • Martin Hope
    user3191334 Como ver as últimas linhas x do log de serviço systemctl 2018-02-07 00:14:16 +0800 CST
  • Martin Hope
    Marko Pacak Nano - pule para o final do arquivo 2018-02-01 01:53:03 +0800 CST
  • Martin Hope
    Kidburla Por que verdadeiro e falso são tão grandes? 2018-01-26 12:14:47 +0800 CST
  • Martin Hope
    Christos Baziotis Substitua a string em um arquivo de texto enorme (70 GB), uma linha 2017-12-30 06:58:33 +0800 CST

Hot tag

linux bash debian shell-script text-processing ubuntu centos shell awk ssh

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