help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Help with String Extraction


From: Steve Matzura
Subject: Help with String Extraction
Date: Mon, 16 Sep 2024 14:06:22 -0400
User-agent: Mozilla Thunderbird Beta

I'm trying to write a script that does the following:


In a loop, list certain files in a directory. For each file:

• Assign a variable to the result of grepping for "<svrinfodesc>" which is always present

• Add 1 to the location of ">" in the string and assign it to a variable

• Assign the location of "</" in the string to a variable

• Assign the difference between the above two values to a variable

• Extract a substring from the original string starting at the first positional variable for a length equal to the number of characters in the calculated length variable

• Display the substring


*** Code ***


#!/bin/sh
for f in $(ls *.xml)
do
  echo $f # Display the filename
  stringZ = $(grep -i svrinfodesc $f) # Find the string I want

  echo $stringZ # Let's see the string
pos1 = `expr index "$string" \>` + 1 # Position of first character after ">"
  pos2 = `expr index "$string" \<\/` # Position of first character after the string
len = (pos2 - pos1) # How long will the substring be?
echo ${stringZ:pos1:len}
done

Test Data:


Create a file (anything.xml will do) with a couple junk lines as long as it includes a line containing the grep target, like this one:


<svrinfodesc>Ham Radio Study Show</svrinfodesc>


Everything I've read about string extraction says I'm doing it right, but nevertheless, the script aborts at that very line. What did I miss?


Thanks in advance.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]