0

I struggle to properly read a file which is nothing else than a key=value file.

This is the file:

#test.txt

global.project=99999 
global.env=pr
global.app=Terraform
global.dcs=CloudBroker
global.cbp=n/a

This is the code:

TS=""
while IFS== read -r f1 f2; do
    echo $f1
    echo $f2
    val=$f2
    TS+="\"${f1}\":\"${f2}\","

done < "tags.txt"

echo "${TS}" # Result: ","global.cbp":"n/audBroker

The result is very strange. When I remove f2, then no issues occur.

The expected result should be:

"global.opco":"99999","global.env":"pr" and so on.

WorkoutBuddy
  • 609
  • 9
  • 23
  • 1
    I think your file has DOS line endings, fix that with `dos2unix` and try again – oguz ismail Jun 16 '20 at 19:24
  • 1
    The test.txt file is in DOS/Windows format, and has a nonprinting carriage return character at the end of each line (in addition to the newline that unix programs expect), and it's getting treated as part of `f2`. See [this question](https://stackoverflow.com/questions/22481278/syntax-error-invalid-arithmetic-operator-error-token-is). In your case, you can trim it by changing the `read` command slightly: `while IFS=$'=\r' read -r f1 f2; do`. – Gordon Davisson Jun 16 '20 at 19:25

2 Answers2

1

Based on the comment by @GordonDavisson, I modified the script and it works now like a charm:


TS=""
while IFS=$'=\r' read -r f1 f2; do
    echo $f1
    echo $f2
    val=$f2
    TS+="\"${f1}\":\"${f2}\","

done < "tags.txt"

echo "${TS}" # Result: {"global.project":"99999","global.env":"pr","global.app":"Terraform","global.dcs":"CloudBroker","global.cbp":"n/a",}

WorkoutBuddy
  • 609
  • 9
  • 23
1

Just a regex:

sed 's/\(.*\)=\(.*\)\r\?/"\1":"\2"/' tags.txt | paste -sd,
#                                                        ^ merge lines with comma
#                        ^  ^^^  ^     add some characters
# put  ^^^^^^             ^^           <- here
# put          ^^^^^^          ^^      <- here
KamilCuk
  • 120,984
  • 8
  • 59
  • 111