用冒号分隔的字符串循环遍历文件

用冒号分隔的字符串循环遍历文件

本文介绍了用冒号分隔的字符串循环遍历文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的文件:

I have a file that looks like this:

work:week:day:england:
work1:week:day:sweden:
work2:week:day::
.....

每次我遍历列表时,我都希望将每个字符串作为变量使用.例如,如果我想知道我在哪个位置工作,我将从第一列工作*"中获得第四个位置列

Each time I loop through the list I want go get each string as a variable which I can use.E.g if I want to know which location I work in I would get the fourth location column from the first column "work*"

我尝试过:

for country in $( awk -F '[:]' '{print $1}' file.txt); do
    if [[ "$country" == "england" ]];
    then
            echo "This user works in England!"
    else
            echo "You do not work in England!"
    fi
done

我想让每个字符串都用冒号分隔,作为每个循环每一行的变量.

I would like to get each strings separated by a colon as a variable for each row each loop.

推荐答案

您可以为此使用bash:将IFS(内部字段分隔符)设置为:,这样可以正确捕获字段:

You can use just bash for this: set IFS (internal field separator) to : and this will catch the fields properly:

while IFS=":" read -r a b c country
do
  echo "$country"
done < "file"

这将返回:


england
sweden

这样,您将能够在第一个字段中使用$a,在第二个字段中使用$b,在第三个字段中使用$c,并在第四个字段中使用$country.当然,请根据您的要求修改编号和名称.

This way you will be able to use $a for the first field, $b for the second, $c for the third and $country for the forth. Of course, adapt the number and names to your requirements.

一起:

while IFS=":" read a b c country
do
   if [[ "$country" == "england" ]]; then
      echo "this user works in England"
   else
      echo "You do not work in England"
   fi
done < "file"

这篇关于用冒号分隔的字符串循环遍历文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:47