0

I have a file (user.txt) with the below content with 90+ users

  • example file content
    user: Ronaldo
    id:7
    endpoint:manutd.com
    user: Messi
    id:30
    endpoint:psg.com
    user: Neymar
    id:10
    endpoint:psg.com
    
  • desired output:
    Ronaldo is in manutd.com and wears no 7
    Messi is in psg.com and wears no 30
    .
    .
    
    and so on for all the users

How can I print this way via a Bash script?

3 Answers3

1

You can use this awk

awk -F: '/user/ {name=$2 " is in "; next} /id/{id="no "$2;next} /endpoint/ {team=$2 " and wears "} {print name, team, id }' $inputfile

Output

 Ronaldo is in  manutd.com and wears  no 7
 Messi is in  psg.com and wears  no 30
 Neymar is in  psg.com and wears  no 10

I am assuming your expected output with capitalization is wrong, but if not, please point this out.

sseLtaH
  • 2,786
1

With sed:

$ sed -n 'N;N;s/^user: *\(.*\)\nid: *\(.*\)\nendpoint: *\(.*\)/\1 is in \3 and wears no \2/p' file
Ronaldo is in manutd.com and wears no 7
Messi is in psg.com and wears no 30
Neymar is in psg.com and wears no 10
1

bash:

declare -A record
while IFS=":$IFS" read -r key value; do
    record[$key]=$value
    if [[ -v 'record[user]' && -v 'record[id]' && -v 'record[endpoint]' ]]; then
        printf '%s is in %s and wears no %s\n' "${record[user]}" "${record[endpoint]}" "${record[id]}"
        record=()
    fi
done < file.content
glenn jackman
  • 85,964