如何在bash shell脚本中将字符串的一部分提取到变量中?

时间:2012-12-07 12:17:21

标签: bash shell sed awk grep

我有一个带有许多行的eclipse .classpath文件,比如

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

我的目的是编写一个bash脚本,它将解析每一行以测试库是否存在。对于奖励积分,因为我知道我的机器上可能存在库的备用位置,如果在类路径文件指定的位置找不到,我也会搜索备用位置并尽可能修复类路径文件。

我该怎么做?

似乎与How can I extract part of a string via a shell script?相关,但不确定如何将其变为类似

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

我认为这是我的目标。

2 个答案:

答案 0 :(得分:2)

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

它不适用于包含换行符或双引号的文件名。如果你有其中任何一个让我们知道。

答案 1 :(得分:0)

首先使用egrep从类路径文件中获取jar路径,然后遍历每个路径。

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