1

Does anyone have an idea on how to remove hidden characters from a string in the shell?

  • This is an example :

    # echo $a;
    [root@localhost ~]#
    
  • But when I "force" display of hidden characters it looks like this:

    # echo $a | cat -v
    [root@localhost ~]# ls ^H^[[K^H^[[K^H^[[Kpwd^H^[[K^H^[[K^H^[[Kls^H^[[K^H^[[Kpwd^H^[[K^H^[[K^H^[[K
    
  • I want to delete hidden characters to have this output:

    # echo $a | cat -v
    [root@localhost ~]#
    
AdminBee
  • 22,803
  • This is a minor variant on https://unix.stackexchange.com/q/14684/5132 . – JdeBP May 20 '19 at 12:33
  • Print the string to the terminal and then copy it back from terminal to your string. – user9101329 Mar 12 '24 at 16:15
  • You can also use tr command to delete everything except the class of characters you want. For example to keep only alphanumeric characters and get rid of everything else: echo $a | tr -dc '[a-zA-Z-0-9]' – user9101329 Mar 12 '24 at 16:19

1 Answers1

0

Use sed to strip out the non-printing characters:

echo $a | sed 's/[^ -~]//g' | cat -v

Or to store it:

a=$(echo $a | sed 's/[^ -~]//g')
  • hello , thank for your answer but in the output it's give me "[@ ~]# [[[[[[[[ [[[[[[[[[[[" i want to have the output without the hidden characters . – Kamal Ezzaki May 20 '19 at 12:30
  • You have not tried out your answer. Try it against the output of printf '[root@localhost ~]# ls \b\e[K\b\e[[K\b\e[Kpwd\b\e[K\b\e[K\b\e[K' to see how wrong it goes. – JdeBP May 20 '19 at 12:31
  • Ah, you also want to remove escape sequences in addition to non-printing characters. A second sed will accomplish that. I'll edit my answer... – L. Scott Johnson May 20 '19 at 12:33
  • ... or nm, see the post JdeBP linked in the comment to the main question. – L. Scott Johnson May 20 '19 at 12:34