使用KSH。我有一个变量,其中包含用双引号引起来并用逗号分隔的字符串,我想遍历这些字符串,我不想将双引号中的逗号识别为分隔符。
我尝试将IFS设置为IFS =“ \”,\“”和IFS =“,”,但是它仍然可以识别双引号内的逗号。
简体:
errorStrings="Some error","Another error","This, error"
oldIFS=$IFS
IFS=","
for error in $errorStrings;do
echo "Checking for $error"
#grep "$error" file >/dev/null 2>&1 && echo "$error found"
continue
done
IFS=$oldIFS
Actual:
Checking for Some error
Checking for Another error
Checking for This
Checking for error
Expected:
Checking for Some error
Checking for Another error
Checking for This, error
答案 0 :(得分:0)
第一个问题是errorStrings
不是您所期望的。试试
echo "e=[${errorStrings}]"
如果要在字符串中使用双引号,请使用
errorStrings='"Some error","Another error","This, error"'
在for循环中引用$errorStrings
时,您的脚本会更好地工作。
oldIFS=$IFS
IFS=","
for error in "$errorStrings";do
echo "Checking for $error"
#grep "$error" file >/dev/null 2>&1 && echo "$error found"
continue
done
IFS=$oldIFS
仍然必须修改此循环才能删除引号。 也许这是使用数组的好时机:
errorStrings=("Some error" "Another error" "This, error")
for error in "${errorStrings[@]}";do
echo "Checking for $error"
#grep "$error" file >/dev/null 2>&1 && echo "$error found"
continue
done
我不确定您的环境中有哪些选择,也许这也行得通:
errorStrings='"Some error","Another error","This, error"'
echo "${errorStrings}" | sed 's/","/"\n"/g' | while read error; do
echo "Checking for $error"
done