shell 如何将字符串拆分为分律并将每个子字符串回显到文件



嗨,我正在尝试拆分从文件中获取的字符串,使用分隔符"<"然后我想将每个字符串回显到文件中。我有点在那里,但不确定如何最好地拆分字符串,然后循环回显每个子字符串(最多可能有 10 个子字符串)我猜我需要创建一个数组来存储这些字符串,然后有一个循环来回显每个值?

这是我到目前为止所拥有的:

while read line
do
   # ceck if the line begins with client_values=
   if[["$line" == *client_values=*]]
        CLIENT_VALUES = 'echo "${line}" | cut -d'=' -f 2'
        #Now need to split the  CLIENT_VALUES using "<" as a delimeter.
        # for each substring
            echo "Output" >> ${FILE}
            echo "Value $substring" >> ${FILE}
            echo "End" >> ${FILE}
    done < ${PROP_FILE}
grep '^client_values=' < "${PROP_FILE}" | while IFS='=' read name value
  do
    IFS='<' read -ra parts <<< "$value"
    for part in "${parts[@]}"
    do
      echo "Output"
      echo "Value $part"
      echo "End"
    done >> "${FILE}"
  done
这里的

一行awk可能更简单(并且您将获得=<愤怒的面部正则表达式分隔符的额外好处)

$ awk -F "[=<]" '/^client_values/ { print "Output"; for (i = 2; i <= NF; i++) print "Value " $i; print "End"}'  input.txt >> output.txt
$ cat input.txt
client_values=firstvalue1<secondvalue2<thirdvalue3
some text
client_values=someothervalue1<someothervalue2
$ cat output.txt
Output
Value firstvalue1
Value secondvalue2
Value thirdvalue3
End
Output
Value someothervalue1
Value someothervalue2
End

您的答案可能也有效,我认为只需进行最少的修改,您就会想要类似的东西

#!/bin/bash
PROP_FILE='input.txt'
FILE="output2.txt"
while read line
do
   # ceck if the line begins with client_values=
   if [[ "$line" == "client_values="* ]]
   then
        CLIENT_VALUES=`echo "${line}" | cut -d'=' -f 2`
        IFS='<' read -ra CLIENT_VALUES <<< "$CLIENT_VALUES"
        for substring in "${CLIENT_VALUES[@]}"; do
          echo "Output" >> "${FILE}"
          echo "Value $substring" >> "${FILE}"
          echo "End" >> "${FILE}"
        done
  fi
done < "${PROP_FILE}"

它产生

$ cat output2.txt
Output
Value firstvalue1
End
Output
Value secondvalue2
End
Output
Value thirdvalue3
End
Output
Value someothervalue1
End
Output
Value someothervalue2
End

虽然再次,不确定这是否是你想要的。

相关内容

  • 没有找到相关文章

最新更新