bash 从一行(变量)中提取列的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29269259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:38:33  来源:igfitidea点击:

Extract value of column from a line (variable)

bashshellunixawk

提问by user4516211

Okay, so I have a variable ($line) that is defined in the bash/shell script as

好的,所以我在 bash/shell 脚本中定义了一个变量($line)

$line = "abc:123:def:345" 

need to get this column2 = "123"

需要得到这个 column2 = "123"

How do I extract the value of the 2nd column i.e. "123" and name it as a different variable which can be summed later on? I know you have to separate it based on the delimiter ':' but I don't know how to transfer to different variable whilst taking input from $line variable. I only ask this because for some weird reason my code reads the first line of text file BUT doesn't perform the awk on just the first line onlyso hence the sum is wrong.

如何提取第二列的值,即“123”并将其命名为一个不同的变量,稍后可以求和?我知道你必须根据分隔符 ':' 将它分开,但我不知道如何在从 $line 变量中获取输入的同时转移到不同的变量。我之所以这么问,是因为出于某种奇怪的原因,我的代码读取了文本文件的第一行,但仅在第一行不执行 awk,因此总和是错误的。

FILE=
while read line
do
 awk -F: '{summation += ;}END{print summation;}'
done < $FILE

-code via shell script

- 通过shell脚本编写代码

Thanks.

谢谢。

回答by Jotne

You can use awkto get second field:

您可以使用awk获取第二个字段:

line="abc:123:def:345"

awk -F: '{print }' <<< "$line"
123

回答by glenn Hymanman

To assign a variable in the shell, no $on the left-hand side, no spaces around the =, and <and >are not valid quote characters

要在 shell 中分配变量,$左侧的 no =, 和周围没有空格,并且<>不是有效的引号字符

line="abc:123:def:345"

In bash, you would do this:

在 bash 中,你会这样做:

IFS=: read -ra fields <<< "$line"
  • temporarily set IFSto a colon
  • use the $linevariable as input to the readcommand (a here-string)
  • and read the values into the fieldsarray.
  • 暂时设置IFS为冒号
  • 使用$line变量作为read命令的输入(一个here-string
  • 并将值读入fields数组。

Bash arrays are indexed starting from zero, so to extract the 2nd field:

Bash 数组从零开始索引,因此要提取第二个字段:

echo "${fields[1]}"   # => 123

回答by glenn Hymanman

way in bash using expr

在 bash 中使用 expr 的方式

Line2=$(expr $line : "[^:]*:\([^:]*\)")

or if the fields are always 3 characters

或者如果字段总是 3 个字符

Line2=${line:4:3}