0
    cat file.txt 
    
    "1" "USA" "abc"
    "2" "Canada" "pqr" 
....

I'm trying to assign the above string values to a variable iterating through each line at a time. For eg. ->

sr="1" country="USA"    name="abc" 
sr="2" country="Canada" name="pqr"

Any advise on how I can achieve this? Thanks

10
  • A little bit more clarifying of what you really want would be appreciated. Do you just want to store all values in an array? Do you want to iterate through each value? What exactly are you trying to achieve? - An example of what you've already tried would be great too. Commented Jan 14, 2022 at 7:18
  • Thanks for your message! I've added an example above to explain what I'm trying to achieve. Commented Jan 14, 2022 at 7:25
  • 1
    while read -r sr country name ; do … ; done < file.txt? Commented Jan 14, 2022 at 7:26
  • 1
    Whoever created this file format should be prepared to receive serious threats to their bodily integrity, perhaps from you. Commented Jan 14, 2022 at 9:05
  • 1
    Perhaps roughly equivalently, sed 's/^"//;s/"$//;s/" "/\t/g' file.txt | while IFS=$'\t' read -r sr country name; do... Demo: ideone.com/bo8iIo Commented Jan 14, 2022 at 9:08

2 Answers 2

1

try this one:

cat 1.txt|awk '{print "str="$1,"country="$2,"name="$3}'
Sign up to request clarification or add additional context in comments.

Comments

1

If the quoting of the data is compatible to the Bash rules for Double Quotes, you can just use set:

#! /bin/bash

exec <<EOF
"1" "USA" "abc"
"2" "Canada" "pqr" 
EOF

while read -r line; do
  source <(printf 'set %s\n' "$line")
  printf 'sr="%s" country="%s" name="%s"\n' "$@"
done

If the quoting of the data is compatible to the JSON quoting rules, you can use jq to parse the data:

#! /bin/bash

exec <<EOF
"1" "USA" "abc"
"2" "Canada" "pqr" 
EOF

jq -sr '.[]' | while true; do
  read -r sr || break
  read -r country
  read -r name
  printf 'sr="%s" country="%s" name="%s"\n' \
         "$sr" "$country" "$name"
done

This will be less prone to security exploits.

3 Comments

You're asking for trouble :-P
@Fravadona The ideas of other people are not much better. Bash is not the right tool to write parsers. You can slurp the data through jq to feel a bit better. But since he did not say anything about the quoting rules: this will work at least for the two lines in the question.
source <(printf 'set %s\n' "$line") is no different from using an eval besides using a subshell and process substitution.

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.