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
ファイル内で一度だけ発生する組み合わせを識別し、それらを3つの変数a
とb
に分割したいとしますc
。この場合、連想配列を使用できます。
次は動作します。
#!/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
ノートこれは次のように仮定します。これらの固有のポートは1つだけです。(あなたの例から推測するのは合理的に見えます)。