在屏幕中间打印代码输出

Neb*_*eez 10 command-line scripts

下面的代码将file在屏幕上逐字输出任何内容。例如:

Hello 将显示 1 秒然后消失。然后,句子中的下一个单词将出现一秒钟然后消失,依此类推。

如何输出屏幕中间显示的任何内容?

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

ter*_*don 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 
Run Code Online (Sandbox Code Playgroud)

将其另存为~/bin/foo.sh,使其可执行 ( chmod a+x ~/bin/foo.sh) 并将您的输入文件作为其第一个参数:

foo.sh file
Run Code Online (Sandbox Code Playgroud)


0x2*_*fa0 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
Run Code Online (Sandbox Code Playgroud)