BASH中文本文件中的多个变量

时间:2022-12-27 22:12:28

I am writing a script to RSH into servers from a text file and create a specific user on each system. I work for a university that is currently testing Amazon EC2 for their courses. Is it possible to take colon or comma separated values in a text file like this :

我正在通过文本文件将RSH脚本编写到服务器中,并在每个系统上创建特定用户。我在一所目前正在测试Amazon EC2课程的大学工作。是否可以在文本文件中使用冒号或逗号分隔值,如下所示:

    server.edu:user123:John:email@university.edu

and pass them to a BASH script as $server $username etc...

并将它们作为$ server $ username等传递给BASH脚本......

2 个解决方案

#1


1  

Yes you can use it like this:

是的你可以像这样使用它:

> s='server.edu:user123:John:email@university.edu'
> IFS=: read server username email <<< "$s"

> echo "$server"
server.edu
> echo "$username"
user123
> echo "$email"
John:email@university.edu

EDIT:: For reading this data from file line by line

编辑::用于逐行从文件中读取此数据

while IFS=: read server username email; do
   echo "$server"
   echo "$username"
   echo "$email"
done < file

#2


0  

It is possible to read lines of colon-separated data from file into an array directly and index into it:

可以直接从文件中读取冒号分隔数据的行并将其编入索引:

while IFS=: read -a userdata; do
    printf "server: %s\n"   "${userdata[0]}"
    printf "username: %s\n" "${userdata[1]}"
    printf "name: %s\n"     "${userdata[2]}"
    printf "email: %s\n"    "${userdata[3]}"
done < data_file

#1


1  

Yes you can use it like this:

是的你可以像这样使用它:

> s='server.edu:user123:John:email@university.edu'
> IFS=: read server username email <<< "$s"

> echo "$server"
server.edu
> echo "$username"
user123
> echo "$email"
John:email@university.edu

EDIT:: For reading this data from file line by line

编辑::用于逐行从文件中读取此数据

while IFS=: read server username email; do
   echo "$server"
   echo "$username"
   echo "$email"
done < file

#2


0  

It is possible to read lines of colon-separated data from file into an array directly and index into it:

可以直接从文件中读取冒号分隔数据的行并将其编入索引:

while IFS=: read -a userdata; do
    printf "server: %s\n"   "${userdata[0]}"
    printf "username: %s\n" "${userdata[1]}"
    printf "name: %s\n"     "${userdata[2]}"
    printf "email: %s\n"    "${userdata[3]}"
done < data_file