[英]cut command in shell script
My shell script look like this 我的shell脚本看起来像这样
i="10 ID:794 A:TX-SPN S:0"
A=`echo $i | cut -d" " -f 3| cut -d":" -f2` # gives TX-SPN
ID=`echo $i | cut -d" " -f 2|cut -d":" -f2` # gives 794
sZeroCount=`echo $i | cut -d" " -f 1` # gives 10
by above commands,I am able to get the values for A,ID,sZeroCount variables, since the value for i contains only one entry, value of i not limited to 1 it may go upto 1000. Is there any better approach in which I can obtain those values. 通过上面的命令,我能够获取A,ID,sZeroCount变量的值,因为i的值仅包含一个条目,所以i的值不限于1,它可能会增加到1000。可以获得这些值。
With an array. 用数组。 Split string
i
with separator space and :
to array a
: 用分隔符和
:
分割字符串i
以数组a
:
i="10 ID:794 A:TX-SPN S:0"
IFS=" :" a=($i)
echo "${a[4]}" # TX-SPN
echo "${a[2]}" # 794
echo "${a[0]}" # 10
With chepner's bugfix: 与chepner的错误修正:
i="10 ID:794 A:TX-SPN S:0"
IFS=": " read -a a <<< "$i"
echo "${a[4]}" # TX-SPN
echo "${a[2]}" # 794
echo "${a[0]}" # 10
With this piece of code you can convert your line into a proper associative array: 通过这段代码,您可以将行转换为适当的关联数组:
declare -A dict
for token in START:$i # choose a value for START that is not a key
do
IFS=: read key value <<< "$token"
dict["$key"]=$value
done
You can dump the result using declare -p dict
: 您可以使用
declare -p dict
转储结果:
declare -A dict='([A]="TX-SPN" [S]="0" [ID]="794" [START]="10" )'
And you can access the contents eg using this: echo "${dict[A]}"
您可以使用以下内容访问内容:
echo "${dict[A]}"
TX-SPN
The start value (the 10
in your example) can be accessed as "${dict[START]}"
. 起始值(示例中为
10
)可以通过"${dict[START]}"
。 Choose a value for START
that doesn't appear as key in your input. 为
START
选择一个不会在输入中显示为键的值。
If you want to iterate over a lot of lines like your $i
, you can do it like this: 如果要遍历像
$i
这样的许多行,可以这样进行:
while read i
do
declare -A dict
# ... add code from above ...
done < input_file
The advantage of using associative arrays is that this way you can access your values in a much more understandable way, ie by using the keys instead of some arbitrary indexes which can easily be mixed up and which need constant maintenance when changing your code. 使用关联数组的优势在于,您可以通过一种更易于理解的方式访问值,即使用键而不是一些容易混在一起并且在更改代码时需要不断维护的任意索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.