4

How can I modify a line after printing it in unix shell.We can delete the line and write again by using \r as shown below,but how can I overwrite on existing line and not delete it completely and get the output as in Expected output below.

Command:

printf "12345";printf "\r67";

Output:

67

Expected Output

67345
3
  • 2
    printf "12345";printf "\r67\n" does the job on my terminal. I am however unable to account for it
    – iruvar
    Aug 28, 2013 at 14:45
  • 2
    @1_CR is correct. You are missing \n.
    – unxnut
    Aug 28, 2013 at 14:49
  • 3
    @1_CR Without that newline, the cursor is left after the 7. What g4ur4v did not post in his/her output is the command prompt (eg, 67>) which overwrote the 345. With the newline, the cursor will move to the next line instead.
    – goldilocks
    Aug 28, 2013 at 14:54

2 Answers 2

7

As discussed in the comments, the problem is where you've left the cursor. For example:

goldilocks@home> echo -n 1234; echo -ne "\r56"
56goldilocks@home>

What happened is the first echo wrote "1234", then the second echo went back to the beginning of the line and printed "56" and exited. The cursor remained after the 6, and the next thing that happened is the shell printed the command prompt, overwriting "34". If you included a newline in the second echo (or removed the -n switch, so that echo will print a newline automatically), you would get:

goldilocks@home> echo -n 1234; echo -e "\r56"
5634
goldilocks@home>

The cursor moved down a line, leaving the "34" behind.

2
  • 2
    Is your username even goldilocks? Too funny.
    – slm
    Aug 28, 2013 at 16:14
  • 1
    @slm : Actually it's Freakin_Finnickity_Goldilocks_the_Magnificent but I edit these things for brevity ;)
    – goldilocks
    Aug 29, 2013 at 9:54
3

You can do this using a little advanced sed expression

printf '%s\n' {1..5} | sed '/1/,/2/{ s/1/6/;s/2/7/;s/\([^\n]*\)\(\n\)\(.*\)/\3\2\1/; }' | tr '\n' ' '

Using awk

printf '%s' {1..5} | awk '{gsub(/12/,"67"); print}'

Using tr

printf '%s' {1..5} | tr '12' '67'
3
  • In the question I asked for overwriting a line that is already printed on shell .But your answer is about passing output of one to another and then printing on the shell,this is not I was looking for.Anyways ,Thanks for answering.
    – g4ur4v
    Aug 28, 2013 at 15:33
  • @g4ur4v at both first examples I'm overriding the printf built-in. In your example you are using a carriage return \r which overrides printfs output. Take this example echo "12345"; printf '\r67\n' Aug 28, 2013 at 15:41
  • What I wanted to stress on your examples is the use of | instead of ; .As per my understanding ; between two commands is like running two commands next to next and both the commands being independent of each other.But in your example, you are redirecting output of one to another.
    – g4ur4v
    Aug 28, 2013 at 16:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .