Monday, November 23, 2009

VBScript: manejo de cadenas de texto

VBScript: manejo de cadenas de texto



Algunas de las funciones más habituales para manipular cadenas de texto son:


Function
Description
InStr
Returns the position of the first occurrence of
one string within another. The search begins at the first character of the
string
InStrRev
Returns the position of the first occurrence of one string
within another. The search begins at the last character of the string
LCase
Converts a specified string to lowercase
Left
Returns a specified number of characters from
the left side of a string
Len
Returns the number of characters in a string
LTrim
Removes spaces on the left side of a string
RTrim
Removes spaces on the right side of a string
Trim
Removes spaces on both the left and the right side of a
string
Mid
Returns a specified number of characters from a
string
Replace
Replaces a specified part of a string with another string a
specified number of times
Right
Returns a specified number of characters from
the right side of a string
Space
Returns a string that consists of a specified number of
spaces
StrComp
Compares two strings and returns a value that represents
the result of the comparison
String
Returns a string that contains a repeating character of a
specified length
StrReverse
Reverses a string
UCase
Converts a specified string to uppercase

(la fuente es: http://www.w3schools.com/VBscript/vbscript_ref_functions.asp)


A menudo, los ficheros que procesamos tienen líneas con varios campos delimitados por algún tipo de carácter. Todos los lenguajes de programación/scripting poseen algun método para procesar cadenas divididas en campos. En VBScript esta función es:

Split(expression[,delimiter[,count[,compare]]])


La descripción de sus parámetros tal y como la muestran en
http://www.w3schools.com/VBscript/func_split.asp

Parameter
Description
expression
Required. A string expression that contains substrings
and delimiters
delimiter
Optional. A string character used to identify substring
limits. Default is the space character
count
Optional. The number of substrings to be returned. -1
indicates that all substrings are returned
compare
Optional. Specifies the string comparison to use.
Can
have one of the following values:

  • 0 = vbBinaryCompare - Perform a binary comparison
  • 1 = vbTextCompare - Perform a textual comparison

Ejemplo de uso:

Se trata de un script que comprueba la existencia de un fichero de texto, y si existe lo abre y lo recorre línea a línea procesando cada una de ellas. Las líneas contienen campos separados por ";" y el script nos muestra primero la línea y a continuación los campos que contiene.

dim oshell
dim fich, fs

'ubicación del fichero de altas
nombre_fich="c:\tmp\altas.txt"

set oshell=createobject("WScript.shell")
set fs=createobject("scripting.FileSystemObject")

'comprobamos que exista el fichero de altas
if not fs.FileExists(nombre_fich) then
  wscript.echo "no existe el fichero "& nombre_fich
  WScript.Quit 4
end if

'Si hemos llegado hasta aquí es que existe y lo abrimos
set fich=fs.OpenTextFile (nombre_fich, 1, "True" )

'Lo recorremos
Do While fich.atEndOfStream <> True
  linea=fich.ReadLine
' Ahora mostramos la línea leída
  wscript.echo linea
' Parseamos los campos
  campos = split(linea,";")
  for each a in campos
    wscript.echo "valor del campo: "&a
  next
Loop

fich.close



Evidentemente, podríamos hacer algo más útil que mostrar la línea, como por ejemplo usar un objeto de tipo shell para ejecutar dsadd user <usuario> -memberof <grupos>

1 comment:

Anonymous said...

Hola profeta desde q he leido tu cuenda de ´´ lo q me saca de mis casillas`` me he dad ocuenta de q eres un genio pienso igual q tu mas q un profeta eres un dios me gustaria estar en contacato contigo porfavor enviame un correo cualquieras a (argenta976@hotmail.com) tu fan Roger.