0

Hi I am trying to split a string am getting from a file, using the delimiter "<" I then want to echo each string to a file. I am sort of there, but am not sure how to best split the string and then loop echo each substring (there may be up to 10 substrings) I am guessing I need to create an array to store these strings and then have a loop to echo each value?

Here is what I have so far:

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}
Pectus Excavatum
  • 3,593
  • 16
  • 47
  • 68

2 Answers2

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
Alfe
  • 56,346
  • 20
  • 107
  • 159
0

One line awk might be simpler here (and you get the added bonus of having the angry face regex separator =<)

$ 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

Your answer could probably also work, I think with minimal modification, you would want something like

#!/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}"

Which produces

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

Though again, not sure if that's what you want or not.

Reinstate Monica Please
  • 11,123
  • 3
  • 27
  • 48