LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   printf-ing escape characters (http://www.linuxquestions.org/questions/programming-9/printf-ing-escape-characters-4175484237/)

waddles 11-11-2013 02:15 PM

printf-ing escape characters
 
I have tried several approaches to building a single string for printf to display but always end up not displaying the red spaces and blank spaces following the escape sequences and printing the escape sequences instead. Here is my code:
Code:

        str1="SCORE: ["
        str2=$"\033[31m"
        str3=`echo "          " | cut -c $k`
        str4=$"\033[0m"
        sp=$(( 10 - $k ))
        str5=`echo "          " | cut -c $sp`
        str6="]"
        str="${str1}${str2}${str3}${str4}${str5}${str6}"
#        str=$str1+$str2+$str3+$str4+$str5+$str6 didn't work either
        printf "%s" "$str"

How does one use escape sequences in printf above?
BTW I also tried without the "$" in front of the escape code in str2 & 4.

druuna 11-11-2013 03:39 PM

If you use the format part in printf (this part: "%s") then all the escaping meeds to be done in the formatting part.

If you leave out the formatting part then the escaping can be done in the string.

Have a look at this:
Code:

#!/bin/bash

TXT1="foo"
TXT2="bar"
GREEN='[32m'
RED='[31m'
RESET='[0m'
printf "\e%s%s\e%s %s\e%s\n" $GREEN $TXT1 $RED $TXT2 $RESET

str1="SCORE: ["
str2='\033[35m'
str3="Some text"
str4='\033[0m'
str5="more chatter"
str6="]"

str="${str1}${str2}${str3}${str4}${str5}${str6}"
printf "$str\n"


perbh 11-11-2013 03:39 PM

never mind - got it all wrong anyways - sorry

*chuckles*, but now I've got it right!~!
Code:

s1="\033[31m]"
s2="\033[30m]"
s="${s1}${s2}"
echo -en | od -a
0000000 esc  [  3  1  m  ] esc  [  3  0  m  ]
0000014

I guess the secret is the '-e'-switch to 'echo'

druuna 11-11-2013 03:56 PM

@perbh: Yep, when using echo you need to do something like:
Code:

GREEN="\033[32m"
TEXT="Hello World"
echo -e $GREEN$TEXT

But this is about printf, not echo.

waddles 11-11-2013 11:30 PM

Thanks to ALL!! Nice explaining druuna the positioning of the escape in the formatting I see is the key. I have been attempting to make use of the printf but I fear I may have been run over by formatting in my early days of FORTRAN.
I am glad perbh brought out echo because in my attempt to employ printf I could have made life simpler from my perspective with echo. Thanks again.

NevemTeve 11-12-2013 02:17 AM

or:
Code:

ESC=$(printf '\033')
GREEN="$ESC[32m"
echo "${GREEN}Hello, green"

works in [s]stupid[/s] strict shells like dash, too


All times are GMT -5. The time now is 01:49 PM.