shell 脚本查找唯一值并将每个值提取到单独的变量中

shell 脚本查找唯一值并将每个值提取到单独的变量中

有一个带有 vname 和 vport 的 file1

Vname vport
xyc    3:4:7
sdf    5:5:5
sft    5:5:5
sfg    3:4:7
szd    1:2:3

获取唯一端口

vport 1:2:3

将它们分开并分配给一个变量,例如 a=1, b=2, c=3

答案1

这回答了你的问题了吗?

#!/bin/bash

# IFS is a special enviroment variable. The character in it will be used
# by 'read' (which is a bash builtin command).
#
# In this case we need space and colon as separators
#
IFS=' :'

# Looping over lines in the file, fo each line read name, a, b, and c.

# "sed 1d" command deletes first line to skip over header ("Vname vport")
#
sed 1d file1 | while read name a b c ; do

    # If it was an empty line, skip and loop to next line
    #
    [ "$name" ] || continue

    # output the variables for demonstration
    #
    echo "name: $name"
    echo "a = $a"
    echo "b = $b"
    echo "c = $c"

    # extra line to separate output of next line
    #
    echo

done

答案2

我假设您想要识别vport在文件中只出现一次的组合,并且想要将其拆分为三个变量abc。在这种情况下,您可以使用关联数组:

以下应该有效:

#!/bin/bash

declare -A counts   # declare `counts` as associative container

# Read the file line-wise
while read vname vport
do
    if [[ "$vname" == "Vname" ]]; then continue; fi # skip header

    # if current 'vport' value not yet encountered, add it to the array
    # with count=1, otherwise increment the value
    if [[ -z "${counts[$vport]}" ]]
    then
        counts[$vport]=1
    else
        let counts[$vport]=${counts[$vport]}+1
    fi
done < file.txt


# Identify which one only occurs once: iterate over all "keys" and
# check which "value" is "1"
found=0
for vp in "${!counts[@]}"
do
    # If such a key was found, split it at the ':' and read the parts
    # into individual variables
    if [[ "${counts[$vp]}" == "1" ]]
    then
        IFS=":"
        read a b c <<< "$vp"
        found=1
        break
    fi
done


# Output the variables if a unique port specification was found
if (( found == 1 ))
then
    echo "Unique port found: a=$a, b=$b, c=$c"
else
    echo "No unique port found!"
fi

笔记这假设有只有一个这样独特的港口(从你的例子中猜测似乎是合理的)。

相关内容