我正在编写一个 shell 脚本,它根据使用 sed 的模式分割字符串行。
#pattern 'string1','string2','string3'
cat $FILENAME | while read LINE
do
firstPart=$(echo "$LINE" | sed -r "s/'(.*)','(.*)','(.*)'/\1/" )
secondPart=$(echo "$LINE" | sed -r "s/'(.*)','(.*)','(.*)'/\2/" )
thirdPart=$(echo "$LINE" | sed -r "s/'(.*)','(.*)','(.*)'/\3/" )
done
我可以使用单独的回声打印它们,但是如果我将它们放在一个回声中,如下所示
#if LINE from FILE is '123','abc','hello'
echo "$firstPart $secondPart"
#this prints " abc" instead of "123 abc"
#try appending a string on echo
echo "$firstPart -"
#this prints " -3" instead of "123 -"
当我尝试在代码中的常量字符串中使用 sed 时,echo 似乎很好。
#Correct Echo
SOMESTRING='123','abc','hello'
firstPart=$(echo "$SOMESTRING" | sed -r "s/'(.*)','(.*)','(.*)'/\1/" )
secondPart=$(echo "$SOMESTRING" | sed -r "s/'(.*)','(.*)','(.*)'/\2/" )
thirdPart=$(echo "$SOMESTRING" | sed -r "s/'(.*)','(.*)','(.*)'/\3/" )
echo "$firstPart $secondPart"
#this prints "123 abc"
当输入是来自 FILE 的 LINE 时,sed 的行为是否正确?我怎样才能让它表现得好像 LINE 包含在代码中并在代码中声明(就像我的第二个示例一样)。