Shell Script: Formato correto das variáveis

Shell Script: Formato correto das variáveis

Eu não sei escrever variáveis ​​comsed

Então, quero fazer a seguinte tarefa usando o loop for:

sed -n '1.200p' arquivo_grande.txt > 1to200.txt
sed -n '201.400p' big_file.txt > 201to400.txt
sed -n '401.600p' big_file.txt > 401to600.txt
sed -n '601.800p' big_file.txt > 601to800.txt
sed -n '801.1000p' big_file.txt> 801to1000.txt
sed -n '1001,1200p' big_file.txt> 1001to1200.txt
sed -n '1201,1400p' big_file.txt> 1201to1400.txt
sed -n '1401,1600p' big_file.txt > 1401to1600.txt
sed -n '1601,1800p' big_file.txt > 1601to1800.txt
sed -n '1801.2000p' big_file.txt> 1801to2000.txt
sed -n '2001,2200p' big_file.txt > 2001to2200.txt
sed -n '2201,2400p' big_file.txt > 2201to2400.txt
sed -n '2401,2600p' big_file.txt > 2401to2600.txt
sed -n '2601,2800p' big_file.txt > 2601to2800.txt
sed -n '2801,3000p' big_file.txt > 2801to3000.txt
sed -n '3001,3200p' big_file.txt > 3001to3200.txt
sed -n '3201,3400p' big_file.txt > 3201to3400.txt
sed -n '3401,3600p' big_file.txt > 3401to3600.txt
sed -n '3601,3800p' big_file.txt > 3601to3800.txt
sed -n '3801,4000p' big_file.txt > 3801to4000.txt

O que eu tentei:

j=0
for ((i=1;i<=3801;i=$i+200))
do
    #echo $m,$n
    j=$j + 200
    sed -n '$i,$j p' big_file.txt  > $ito$j.txt 
done

Por favor me ajude a fazer isso. Por favor, forneça explicações também.

Responder1

Eu faria isso com um único programa awk, em vez de chamar sedNvezes

awk '
    BEGIN {incr = 200; i=1-incr; j=0}
    NR % incr == 1 {
        i += incr
        j += incr
        close(out)
        out = i "to" j ".txt"
    }
    {print > out}
' big_file.txt

Isso deve ser mais rápido, pois você só precisa processar o arquivo grande uma vez, em vez de 4000÷200=20 vezes.

Responder2

Fechar.

Em j=$j + 200, você precisa invocar explicitamente a expansão aritmética, ou seja j=$(( j + 200 )),.

E em sed -n '$i,$j p' big_file.txt > $ito$j.txt, 1) você precisa usar aspas duplas em vez de aspas simples no argumento para sed, caso contrário, the $será interpretado literalmente e as variáveis ​​não serão expandidas; 2) você precisa de colchetes ao redor i, pois $itoseria uma expansão de variável válida.

Além disso, em contextos aritméticos você não precisa (e provavelmente não deveria) usar o $na frente do nome da variável.

Então, eu reescreveria isso como:

j=0
for (( i = 1 ; i <= 3801 ; i = i + 200)); do
    j=$((j + 200))
    sed -n "$i,$j p" big_file.txt > "${i}to$j.txt"
done

Como outros comentaram, provavelmente há uma maneira melhor de fazer isso, já que agora você percorre o arquivo completo uma vez para cada peça dividida.

informação relacionada