在 bash 中初始化多个变量

Initializing multiple variables in bash

我有一个包含以下内容的文件:

$ cat init
Sample text
PM1:alex:1.2.3.4:22:passwordPM
PM2:alice:5.6.7.8:1212:Password
PM3:bob:9.10.11.12:1313:p@ssword
Some other text

现在我想从 PM1 到 PM3,我想设置一些变量并在我的脚本中使用它们:

user1="alex"
ip1="1.2.3.4"
port1="22"
pass1="password"
...

我需要一个可以用在PM1到PM3以上的结构。可能我也有PM10.

很明显,我们可以 grep 每个字段,但我不知道如何使用它们。

grep PM init | cut -d: -f2
grep PM init | cut -d: -f3
grep PM init | cut -d: -f4
# I need to grep field number 5 in this way:
grep PM init | cut -d: -f5-

更新

如果第三个字母是数字,我需要grep PM。因为如果我不这样做,它可能会与密码(最后一个字段)混淆。

即使不是最慢的 bash shell 大型 data/size 文件的解决方案。

#!/usr/bin/env bash

while read -r lines; do
  if [[ $lines == PM[0-9]* ]]; then
    IFS=: read -r pm user ip port pass <<< "$lines"
    n=${pm#*??}
    printf -v output 'user%s="%s"\nip%s="%s"\nport%s="%s"\npass%s="%s"' "$n" "$user" "$n" "$ip" "$n" "$port" "$n" "$pass"
    array+=("$output")
  fi
done < init

printf '%s\n' "${array[@]}"

array 可以在每个条目中分隔一行,因为当前解决方案将每个 PM[0-9]* 的赋值和值分组,如果您遍历 array 它应该显示什么我说的是。

for i in "${array@]}"; do
  echo "$i"
  echo
done

这是数组值和赋值的单独条目,它可以根据您的操作替换当前的 array 结构。

printf -v user 'user%s="%s"' "$n" "$user"
printf -v ip 'ip%s="%s"' "$n" "$ip"
printf -v port 'port%s="%s"' "$n" "$port"
printf -v pass 'pass%s="%s"' "$n" "$pass"
array+=("$user" "$ip" "$port" "$pass")

一个sed命令就可以做到(使用GNU sed,inputfile将替换为实际输入的文件名):

sed -E -n 's/^PM([0-9]+):([^:]*):([^:]*):([^:]*):(.*)/user=""\nip=""\nport=""\npass=""/p' inputfile

产出

user1="alex"
ip1="1.2.3.4"
port1="22"
pass1="passwordPM"
user2="alice"
ip2="5.6.7.8"
port2="1212"
pass2="Password"
user3="bob"
ip3="9.10.11.12"
port3="1313"
pass3="p@ssword"

您可以像这样在脚本中嵌入这些生成的变量:

#!/bin/bash

# Generate name=value pairs from inputfile and save them in a temporary file /tmp/variables
sed -E -n 's/^PM([0-9]+):([^:]*):([^:]*):([^:]*):(.*)/user=""\nip=""\nport=""\npass=""/p' inputfile > /tmp/variables || exit

# "Source" the file into script 
. /tmp/variables
# Temporary file is not needed any longer. You can remove it if you want

# You can use generated variable names from now on:
echo "user1=$user1"
# and the like