我正在尝试搜索位于4-7号字符中的精确字符串。当我在终端上运行cut
命令时,它可以工作,但是在脚本中它失败了,因为我相信if语句会给我提供"0“。这就是我所做的:
for NAME in `cat LISTS_NAME`; do
if [[ John == cut -c 4-7 "${NAME}" ]]; then
Do Something ...
fi
if [[ Dana == cut -c 4-7 "${NAME}" ]]; then
Do Something...
fi
你能建议我如何使用cut
或任何其他的reg-ex来运行这个吗?
发布于 2015-02-13 01:01:06
你的脚本有很多问题,你不需要cut
。这样使用它:
while read -r line; do
if [[ "${line:3:4}" == "John" ]]; then
Do Something ...
elif [[ "${line:3:4}" == "Dana" ]]; then
Do Something...
fi
done < LISTS_NAME
在BASH中,"${line:3:3}"
与cut -c 4-7
相同
EDIT:如果你不想要精确的字符串匹配,你可以使用:
while read -r line; do
if [[ "${line:3}" == "John"* ]]; then
Do Something ...
elif [[ "${line:3}" == "Dana"* ]]; then
Do Something...
fi
done < LISTS_NAME
发布于 2015-02-13 01:01:59
您并没有在那里运行cut
命令。您正在将John
和Dana
与文字字符串 cut -c 4-7 <value-of-$NAME>
进行比较。
您需要使用:
if [[ John == $(cut -c 4-7 "${NAME}") ]]; then
等。
也就是说,您应该只执行一次cut调用,并将其存储在一个变量中。为了精确匹配,您需要在==
的右侧加上引号,以避免全局匹配。所以
substr=$(cut -c 4-7 "${NAME}")
if [[ John == "$substr" ]]; then
然后,为了避免需要重复的if ...; then
行,您可以使用case
语句做得更好:
substr=$(cut -c 4-7 "${NAME}")
case $substr in
John)
Do something
;;
Dana)
Do something else
;;
esac
https://stackoverflow.com/questions/28483305
复制相似问题