3

I have a properties file which has a password field (key value pair)

PASSWORD=NDhhHcsOBofXUdUzGw5B0Q==

I am trying to get the value in my shell script using the awk command

password=`awk -F "=" '{if($1 == "PASSWORD") print $2}' "$PASSWORD.ini"`

But it retrieves only NDhhHcsOBofXUdUzGw5B0Q.

I need the entire password (including the last two = characters).

2
  • Are you base64 encoding passwords?
    – user26112
    Jul 29 '13 at 13:37
  • @Evan, yes, that's base64 and if you look at the unencoded value, it's a 16 byte value, so probably a MD5 hash of the password. Jul 29 '13 at 14:27
5
password=$(sed -n 's/^PASSWORD=//p' < "$PASSWORD.ini")
4

cut would be the appropriate tool here if you already have the line extracted:

$ echo 'PASSWORD=NDhhHcsOBofXUdUzGw5B0Q==' | cut -d= -f2-
NDhhHcsOBofXUdUzGw5B0Q==

Here, you're taking fields from the 2nd to the end.

GNU grep with perl regular expressions would also work:

pw=$(grep -oP '^PASSWORD=\K.*' < filename)
0
4

Using awk:

password=$(awk 'sub(/^PASSWORD=/,"")' < "$PASSWORD.ini")
2

Using awk you are not limited to splitting on single characters. So you could split on D= for example or even PASSWORD=:

password=$(awk -F "D=" '{print $2}' $PASSWORD.ini)

or

password=$(awk -F "PASSWORD=" '{print $2}' $PASSWORD.ini)
2

There's several nice ways you can do this within awk depending on the particular approach that suits you:

Change your FS:

$ echo 'PASSWORD=NDhhHcsOBofXUdUzGw5B0Q==' | awk -FPASSWORD= '{print $2;}'
NDhhHcsOBofXUdUzGw5B0Q==

Or change your ORS (this is REALLY hacky):

$ echo 'PASSWORD=NDhhHcsOBofXUdUzGS="="; ORS="=";} {for (i=2;i<NF;i++) print $i}'
NDhhHcsOBofXUdUzGw5B0Q==

The robust and generic way:

$ echo 'PASSWORD=NDhhHcsOBofXUdUzGw5B0Q==' | awk 'BEGIN {FS="^[^=]+=";} {print $2;}'
NDhhHcsOBofXUdUzGw5B0Q==

or (in the case of parsing >1 line and finding the one for which you are searching):

$ echo -e 'foo=bar\nPASSWORD=NDhhHcsOBofXUdUzGw5B0Q==\nbaz=quux\n\n' | \
  awk 'BEGIN {FS="^[^=]+=";} /^PASSWORD=/ {print $2;}'
NDhhHcsOBofXUdUzGw5B0Q==
3
  • Isn't missing the awk call itself from the second code block?
    – manatwork
    Jul 29 '13 at 15:56
  • … which is handled by the final example.
    – MikeyB
    Jul 29 '13 at 16:43
  • Oops, indeed. Sorry, I missed that.
    – manatwork
    Jul 29 '13 at 16:55
2

Using Bash:

while read line ; do
  case $line in
    PASSWORD=*)
      echo "${line#PASSWORD=}" ;;
  esac
done < "$PASSWORD.ini"

The ${variable#text} part strips the text from the variable.

0
1

And here's a Perl one:

pw=$(perl -ne 'print $1 if /PASSWORD=(.+)/' "$PASSWORD.ini")

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.