1

I want to print in the Terminal something like this:

lollipop
lollipo
lollip
lolli
loll
lol
lo
l

However if i do -n twice i get a newline and then it just prints "-n" if i use echo. How can i avoid this from happening and make this mess not print when i run X:

lollipop
lollipo-nlollip-nlolli-nloll-nlol-nlo-nl

X:

echo lollipop -n lollipo -n lollip -n lolli -n loll -n lol -n lo -n l
10
  • 1
    Use printf instead: printf "lollipop\nlollipo\nlollip\nlolli\nloll\nlol\nlo\nl"
    – Eddie Dunn
    Dec 8, 2015 at 21:46
  • It would be clearer if you could add spaces, like this: printf "\\\lollipop\nlollipo\nlollip\nlolli\nloll\nlol\nlo\nl\\\"
    – Star OS
    Dec 8, 2015 at 21:47
  • 2
    Why echo and not something better?
    – muru
    Dec 8, 2015 at 21:48
  • People are downvoting this for what? The fact it uses echo? My last post had around 15 upvotes and the accepted answer 30 upvotes and it mostly used echo.
    – Star OS
    Dec 8, 2015 at 21:50
  • Side note: -n removes the trailing newline, it doesn't add it. And the main problem is even if it added it, you pass a single string to echo.
    – kos
    Dec 8, 2015 at 21:52

3 Answers 3

8

You need to use the -e "enable interpretation of backslash escapes" option with the \n to force newlines

echo -e "lollipop\nlollipo\nlollip\nlolli\nloll\nlol\nlo\nl"
0
2

Use printf instead:

printf "lollipop\nlollipo\nlollip\nlolli\nloll\nlol\nlo\nl"

1
  • "using echo" I'll change everything if i see this works.
    – Star OS
    Dec 8, 2015 at 21:46
2

Prefer high level and portable tools for special formatting instead of such tools as echo. Here I am using AWK to print the ever decreasing substring that was provided with here-string . Note that I could have used printf "%s" lollipop | awk . . . as well for better portability

$ awk '{for(i=length($1);i>=1;i--) print substr($1,1,i)}' <<< "lollipop"       
lollipop
lollipo
lollip
lolli
loll
lol
lo
l

AWK's print function always prints a single line, similar to java's System.out.println. This could be replaced with print "%s\n",substr($1,1,i)

1
  • Hey, it works too.
    – Star OS
    Dec 8, 2015 at 22:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.