Друк виводу коду в середині екрана


10

Код, наведений нижче, fileна екрані виводить все слово в слово. Наприклад:

Hello відображатиметься протягом 1 секунди і зникає. Потім наступне слово в реченні з’явиться на секунду і зникне тощо.

Як вивести все, що відображається посередині екрана?

awk '{i=1; while(i<=NF){ print $((i++)); system("sleep 1; clear") }}' file

Чого саме ви намагаєтесь досягти?
муру

ця команда відображає кожне слово-слово у верхньому лівому куті екрана. Мені потрібно знати, як зробити висновок посередині екрана.
Nebelz Cheez

4
Так, але чого ви намагаєтесь досягти? Це звучить як проблема XY ,
muru

Що таке "середина екрану"? Середина терміналу? Середина фактичного екрана? Що робити, якщо ви зміните розмір терміналу, чи потрібно вам це для динамічного розміщення тексту посередині, незалежно від розміру терміналу?
тердон

так. Середина терміналу.
Nebelz Cheez

Відповіді:


7

Ось вам дуже надійний сценарій баш:

#!/bin/bash

## When the program is interrupted, call the cleanup function
trap "cleanup; exit" SIGHUP SIGINT SIGTERM

## Check if file exists
[ -f "$1" ] || { echo "File not found!"; exit; }

function cleanup() {
    ## Restores the screen content
    tput rmcup

    ## Makes the cursor visible again
    tput cvvis
}

## Saves the screen contents
tput smcup

## Loop over all words
while read line
do
    ## Gets terminal width and height
    height=$(tput lines)
    width=$(tput cols)

    ## Gets the length of the current word
    line_length=${#line}

    ## Clears the screen
    clear

    ## Puts the cursor on the middle of the terminal (a bit more to the left, to center the word)
    tput cup "$((height/2))" "$((($width-$line_length)/2))"

    ## Hides the cursor
    tput civis

    ## Prints the word
    printf "$line"

    ## Sleeps one second
    sleep 1

## Passes the words separated by a newline to the loop
done < <(tr ' ' '\n' < "$1")

## When the program ends, call the cleanup function
cleanup

8

Спробуйте сценарій нижче. Він визначить розмір терміналу для кожного вхідного слова, тому навіть динамічно оновлюватиметься, якщо змінити розмір терміналу під час його роботи.

#!/usr/bin/env bash

## Change the input file to have one word per line
tr ' ' '\n' < "$1" | 
## Read each word
while read word
do
    ## Get the terminal's dimensions
    height=$(tput lines)
    width=$(tput cols)
    ## Clear the terminal
    clear

    ## Set the cursor to the middle of the terminal
    tput cup "$((height/2))" "$((width/2))"

    ## Print the word. I add a newline just to avoid the blinking cursor
    printf "%s\n" "$word"
    sleep 1
done 

Збережіть його як ~/bin/foo.sh, зробіть його виконуваним ( chmod a+x ~/bin/foo.sh) і дайте йому вхідний файл як його перший аргумент:

foo.sh file

3

функція bash, щоб зробити те саме

mpt() { 
   clear ; 
   w=$(( `tput cols ` / 2 ));  
   h=$(( `tput lines` / 2 )); 
   tput cup $h;
   printf "%${w}s \n"  "$1"; tput cup $h;
   sleep 1;
   clear;  
}

і потім

mpt "Text to show"

1
Це здається точно таким же, як і моя відповідь, за винятком того, що воно показує одне, а не кожне слово речення, прочитане з файлу окремо, як цього вимагає ОП.
тердон

1

Ось Python скрипт , який схожий на @ Helio в bashрозчині :

#!/usr/bin/env python
import fileinput
import signal
import sys
import time
from blessings import Terminal # $ pip install blessings

def signal_handler(*args):
    raise SystemExit

for signal_name in "SIGHUP SIGINT SIGTERM".split():
    signal.signal(getattr(signal, signal_name), signal_handler)

term = Terminal()
with term.hidden_cursor(), term.fullscreen():
    for line in fileinput.input(): # read from files on the command-line and/or stdin
        for word in line.split(): # whitespace-separated words
            # use up to date width/height (SIGWINCH support)
            with term.location((term.width - len(word)) // 2, term.height // 2):
                print(term.bold_white_on_black(word))
                time.sleep(1)
                print(term.clear)
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.