1

I have some text with a password which may contain special characters (like /, *, ., [], () and other that may be used in regular expressions). How to remove that password from the text using Korn shell or maybe sed or awk? I need an answer which would be compatible with Linux and IBM AIX.

For example, the password is "123*(/abc" (it is contained in a variable). The text (it is also contained in a variable) may look like below: "connect user/123*(/abc@connection_string"

As a result I want to obtain following text: "connect user/@connection_string"

I tried to use tr -d but received wrong result:

l_pwd='1234/\@1234'
l_txt='connect target user/1234/\@1234@connection'
print $l_txt | tr -d $l_pwd

connect target user\connection
Prokhozhii
  • 622
  • 1
  • 8
  • 12

2 Answers2

1

tr -d removes all characters in l_pwd from l_txt that's why the result is so strange.

Try this:

l_pwd="1234/\@1234";
escaped_pwd=$(printf '%s\n' "$l_pwd" | sed -e 's/[]\/$*.^[]/\\&/g')
l_txt="connect target user/1234/\@1234@connection";
echo $l_txt | sed "s/$escaped_pwd//g";

It prints connect target user/@connection in bash at least.

Big caveat is this does not work on newlines, and maybe more, check out where I got this solution from.

Matthias
  • 3,160
  • 2
  • 24
  • 38
0

With ksh 93u+

Here's some parameter expansion madness:

$ echo "${l_txt//${l_pwd//[\/\\]/?}/}"
connect target user/@connection

That takes the password variable, substitutes forward and back slashes into ?, then uses that as a pattern to remove from the connection string.


A more robust version:

x=${l_pwd//[^[:alnum:]]/\\\0}
typeset -p x                        # => x='1234\/\\\@1234'

conn=${l_txt%%${x}*}${l_txt#*${x}}
typeset -p conn                     # => connect target user/@connection
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • l_txt='connect target user/o123*/.[]@connection_string'; l_pwd='o123*/.[]'; echo "${l_txt//${l_pwd//[\/\\]/?}/}" ksh: "${l_txt//${l_pwd//[\/\\]/?}/}": 0403-011 The specified substitution is not valid for this command. – Prokhozhii Sep 15 '22 at 15:20
  • This is not only for slashes. All possible regexp characters may present in l_pwd (like /, *, [, ] and so on). There are no limitations on them – Prokhozhii Sep 15 '22 at 15:22
  • Can use `${l_pwd//[^[:alnum:]]/?}` but that might lead to false positives. I was trying to simply escape special characters (`${l_pwd//[^[:alnum:]]/\\\0}`) but couldn't get that working – glenn jackman Sep 15 '22 at 15:33
  • Nope, sorry. The same error "ksh: "${l_pwd//[^[:alnum:]]/?}": 0403-011 The specified substitution is not valid for this command." – Prokhozhii Sep 15 '22 at 15:40
  • What version of ksh? I'm testing with `93u+` – glenn jackman Sep 15 '22 at 15:52
  • It is definitely not ksh93. Something older IBM AIX has. – Prokhozhii Sep 15 '22 at 15:58
  • Do you have `perl` available? `echo "$l_txt" | perl -spe 's/\Q$pw\E//' -- -pw="$l_pwd"` – glenn jackman Sep 15 '22 at 16:36