화면 중간에 코드 출력 인쇄


10

아래 코드 file는 화면 에 단어 단위로 단어를 출력 합니다. 예를 들면 다음과 같습니다.

Hello 가 1 초 동안 표시되고 사라집니다. 그러면 문장의 다음 단어가 잠시 나타나고 사라집니다.

화면 중간에 표시되는 내용을 어떻게 출력합니까?

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

정확히 달성하려는 것은 무엇입니까?
muru

이 명령은 화면의 왼쪽 상단에 각 단어를 파일로 표시합니다. 화면 중간에 출력하는 방법을 알아야합니다.
Nebelz Cheez

4
예,하지만 무엇을 달성하려고합니까? 같은이 소리 XY 문제 ,
muru

"화면 중간"이란 무엇입니까? 터미널의 중간? 실제 화면의 중간? 터미널의 크기를 조정하는 경우 터미널의 크기에 상관없이 텍스트를 중간에 동적으로 배치하려면 이것이 필요합니까?
terdon

예. 터미널 중간.
Nebelz Cheez

답변:


7

다음은 매우 강력한 bash 스크립트입니다.

#!/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
이것은 OP의 요청에 따라 파일에서 개별적으로 읽은 한 문장의 단어를 모두 보여주는 것이 아니라는 점을 제외하고는 내 대답과 정확히 같습니다.
terdon

1

@Helio의 bash솔루션 과 유사한 Python 스크립트는 다음과 같습니다 .

#!/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)
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.