Question

i have an input file as follow:

some lines with quote and :
AGE:23
some lines with quote and :
NAME:2,0,"My Name Is"
some lines with quote and :

Actually i use this code to extract information from the file:

  age="$(cat "$file" | awk -F ':' '/AGE:/ { print $2 }')"
  name="$(cat "$file" | awk -F '"' '/NAME:/ { print $2 }' )"
  echo "age: $age"
  echo "name: $name"

output:

age: 23
name: My Name Is

i'm searching for a better way to do this than running cat and awk two times. i have search to do it in one cat/awk line but can't figure it out, not appropriated in this case? can anyone point me a better way please ?

Thanks in advance

Was it helpful?

Solution 2

I like @JohnKugelman's approach, but it can be improved: use colon and quote as the field separators:

while IFS=':"' read -ra fields; do 
    case ${fields[0]} in 
        AGE)  age=${fields[1]}  ;; 
        NAME) [[ ${fields[1]} == "2,0," ]] && name=${fields[2]} ;; 
    esac
done < file

With awk, I'd write:

read age name < <(
    awk -F '[:,]' '
        $1 == "AGE" {printf "%s ",$2} 
        $1 == "NAME" && $2 == 2 && $3 == 0 {printf "%s ",$NF} 
        END {print ""}
    ' filename 
)

OTHER TIPS

while IFS=: read key value; do
    case $key in
        AGE)  age=$value;;
        NAME) name=$(awk -F'"' '{print $2}' <<< "$value");;
    esac
done < "$file"

If the data is simple as you have shown in your question. No need to use shell for this , just awk will be more than enough

awk -F '"' '/AGE/{print tolower($0)}/NAME/{print "name:"$2}' input.txt
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top