Domanda

I'm reading in values from an .ini file, and sometimes may get trailing or leading whitespace.

How do I amend this first line to prevent that?

db=$(sed -n 's/.*DB_USERNAME *= *\([^ ]*.*\)/\1/p' < config.ini);
echo -"$db"-

Result;

-myinivar -

I need;

-myinivar-
È stato utile?

Soluzione 2

You don't need the .* inside the capturing group (or the semicolon at the end of line):

db="$(sed -n 's/.*DB_USERNAME *= *\([^ ]*\).*/\1/p' < config.ini)"

To elaborate:

  1. .* matches anything at all
  2. DB_USERNAME matches that literal string
  3. * (a single space followed by an asterisk) matches any number of spaces
  4. = matches that literal string
  5. * (a single space followed by an asterisk) matches any number of spaces
  6. \( starts the capturing group that is used for \1 later
    1. [^ ] matches anything which is not a space character
    2. * repeats that zero or more times
  7. \) ends the capturing group
  8. .* matches anything at all

Therefore, the result will be all the characters after DB_USERNAME = and any number of spaces, up to the next space or end of line, whichever comes first.

Altri suggerimenti

Use parameter expansion.

echo "=${db% }="

You can use echo to trim whitespace:

db='myinivar '
echo -"$(echo $db)"-
-myinivar-

Use crudini which handles these ini file edge cases transparently

db=$(crudini --get config.ini '' DB_USERNAME)

To get rid of more than one trailing space, use %% which removes the longest matching pattern from the end of the string

echo "=${db%% *}="

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top