shell bash - 如何根据分隔符拆分字符串并将每个子字符串回显到文件

时间:2014-01-13 12:03:41

标签: bash shell ksh

您好我正在尝试使用分隔符“<”分割从文件中获取的字符串然后我想将每个字符串回显到一个文件。我有点,但不知道如何最好地分割字符串然后循环回显每个子字符串(可能有多达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}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

这一行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

虽然又一次,不确定这是不是你想要的。