有回声和grep替换每次for循环更改n

时间:2011-06-28 08:38:56

标签: bash

我的文本文件“testnum”如下所示:

xxx1abc
xxx2abc
xxx3abc
xxx4abc
xxx5abc
xxx6abc
xxx7abc
xxx8abc
xxx9abc
xxx10abc..etc

这在cmdline中提供了我想要的输出

for n in {1..10}
do
o=`sed -n "${n}p" < testnum`
clear
echo -e "you read ${o}\r"
grep  -n -C 2 ${o} testnum 
sleep 2s
done

看起来像这就是我想要的

you read xxx10abc
8-xxx8abc
9-xxx9abc
10:xxx10abc
11-xxx11abc
12-xxx12abc

只是它每次迭代时都会清除cmd行 我想要的是这个

nikola@nikola-desktop:~/Downloads$bash my_skirpt
you read xxx1abc
1:xxx1abc
2-xxx2abc
3-xxx3abc

最后一次迭代应该是

nikola@nikola-desktop:~/Downloads$bash my_skirpt
    you read xxx10abc
    8-xxx8abc
    9-xxx9abc
    10:xxx10abc
    11-xxx11abc
    12-xxx12abc
nikola@nikola-desktop:~/Downloads$

1 个答案:

答案 0 :(得分:1)

我不完全确定,但我认为您希望它覆盖最后一次迭代打印的所有行?在这种情况下,您想使用tput

#!/bin/bash
tput sc
for n in {1..10}
do
o=`sed -n "${n}p" < testnum.txt`
echo -e "you read ${o}\r"
grep  -n -C 2 ${o} testnum.txt
sleep 2s
tput rc
tput el1
done;
tput sc

tput sc保存当前光标位置,以便稍后我们可以使用tput rc调用此位置。 tput el1清除我们所在的行,以便更改行数(第一个和最后一个输出比其他输出更短)不会破坏任何内容。

您可以使用tput做更多的事情,例如google将为您提供this页面,我觉得这很不错。