joewyrembelski
joewyrembelski

Reputation: 156

How can I extract a portion of a string into a variable in a bash shell script?

I have an eclipse .classpath file with many lines like

<classpathentry kind="lib" path="/somepath/somelibrary.jar"/>

My intention is to write a bash script that will parse each line to test if the library exists. For bonus points, since I know an alternate location on my machine where the library may exist, if not found in the location specified by the classpath file, I'll search the alternate location also and repair the classpath file if possible.

How can I do this?

Seems like How can I extract part of a string via a shell script? is related, but not sure how to get it into a format like

#!/bin/sh
while read f
do
   if [ -f $f ]
   then
      echo "Found: $f"
   else
      echo "Missing: $f"
   fi
done < $1

Which I think is my goal.

Upvotes: 0

Views: 334

Answers (2)

timtofan
timtofan

Reputation: 104

Use egrep to get the jar paths out of the classpath file first, then iterate over each of those paths.

for f in $(egrep -o '[/a-zA-Z0-9]+\.jar' .classpath); do
   if [ -f $f ]
   then
       echo "Found: $f"
   else
      echo "Missing: $f"
  fi
done

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203169

sed -n 's/.*path="\([^"]*\)".*/\1/p' file |
while IFS= read -r file
do
   if [ -f "$f" ]
   then
      echo "Found: $f"
   else
      echo "Missing: $f"
   fi
done

It won't work for file names containing newlines or double quotes. If you have either of those let us know.

Upvotes: 2

Related Questions