Deleting echo line in bash

2019-02-16 03:11发布

问题:

var=ab
echo -n "$var"

Output: ab

var=abc
echo "$var"

Output: ababc

I want to delete the first ab and replace it by abc

How would I do that?

Regards, intelinside

回答1:

Perhaps you are looking for something like:

var=ab
echo -n "$var"
var=abc
echo -e "\r$var"

This doesn't actually delete anything, but merely moves the cursor to the beginning of the line and overwrites. If the text being written is too short, the content of the previous write will still be visible. You can either write spaces over the old text (very easy and portable):

printf "\r%-${COLUMNS}s" "$var"

or use some terminal escape sequences to delete the old text (not portable):

echo -e "\r$var\033[K"

to move to the beginning of the line, write new text, and then delete from the cursor to the end of the line. (This may not work, depending on the terminal.)