如何在bash中使用多个变量

如何在bash中使用多个变量

user.txt我有一个包含以下内容的文件 ( ),有 90 多个用户

  • 示例文件内容
    user: Ronaldo
    id:7
    endpoint:manutd.com
    user: Messi
    id:30
    endpoint:psg.com
    user: Neymar
    id:10
    endpoint:psg.com
    
  • 期望的输出:
    Ronaldo is in manutd.com and wears no 7
    Messi is in psg.com and wears no 30
    .
    .
    
    对于所有用户等等

如何通过 Bash 脚本以这种方式打印?

答案1

你可以用这个awk

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

输出

 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

我假设您的预期大写输出是错误的,但如果不是,请指出这一点。

答案2

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

答案3

重击:

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

相关内容