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.

2
  • 1
    I think your file has DOS line endings, fix that with dos2unix and try again Commented Jun 16, 2020 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. In your case, you can trim it by changing the read command slightly: while IFS=$'=\r' read -r f1 f2; do. Commented Jun 16, 2020 at 19:25

2 Answers 2

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",}

Sign up to request clarification or add additional context in comments.

Comments

1

Just a regex:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.