读取文件并将每一行拆分为多个变量 [英] read a file and split each line into multiple variables

查看:47
本文介绍了读取文件并将每一行拆分为多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,其中包含文本,如下所示:

I have a file with text inside of it like so:

471_068 0
AALIAN  1
ASHLEY-U    95
CATRIONA_W  97
STESSY K    08

此数据与名称"项目相关,并且是颜色ID"
我需要从ID拆分Name并将它们放在单独的变量中.

This data is related to an items "Name" and it's "Color ID"
I need to split the Name from the ID and house them in separate variables.

请注意,使用小于10的数字时,ID都可以带0或不带0的前导,因此我需要解析它们的出现(04需保留04,而1需保留1而不是4或01)

As a note, the ID when using a digit under 10 can both have a leading 0 or not, so I need to parse those as they appear (a 04 will need to stay 04 and a 1 will need to remain 1 not 4 or 01)

名称中可以包含下划线(_),连字符(-)或空格().

The Names can have an underscore(_), hyphen(-) or space ( ) in them which would need to be preserved as well.

这是我读取文件所需要的,它在循环中逐行读取文件,这很棒,但是我不知道如何正确获取想要分离的变量.

Here is what I have for reading the file, which reads the file line by line in the loop which is great but I can't figure out how to get the variables I want separated correctly.

while read fLine
do
  PRDT=$(echo $fLine | tr '\t' '\n')
  echo First Var is ${PRDT[0]} - Second Var is ${PRDT[1]}
done < Products

推荐答案

read 可以自行完成此操作.参见 BashFAQ#1 .

read can do this itself. See BashFAQ #1.

while IFS=$'\t' read -r key value; do
  echo "First Var is $key - Remaining Line Contents Are $value"
done

请注意,如果您要舍弃第二列之后的任何内容(而不是将该内容附加到值上),则应为:

Note that if you want to discard any content after the second column (rather than appending that content to the value), this would instead be:

while IFS=$'\t' read -r key value _; do
  echo "First Var is $key - Second Var is $value"
done

如果您要以能够按名称查找ID的方式存储ID,则正确的工具是关联数组(在bash 4.0中添加):

If you want to store the IDs in such a way as to be able to look them up by name, an associative array (added in bash 4.0) is the right tool:

declare -A color_ids=( )
while IFS=$'\t' read -r key value; do
  color_ids[$key]=$value
done

for name in "${!color_ids[@]}"; do
  value=${color_ids[$name]}
  echo "Stored name $name with value $value"
done

这篇关于读取文件并将每一行拆分为多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆