KSH:遍历双引号逗号分隔变量
KSH: Loop through a double quoted comma separated variable
使用 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
第一个问题是 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
使用 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
第一个问题是 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