bash - 使用冒号分隔的字符串遍历文件

标签 bash loops awk

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

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

每次我循环遍历列表时,我都希望将每个字符串作为我可以使用的变量。 例如,如果我想知道我在哪个位置工作,我将从第一列“工作*”中获取第四个位置列

我试过这个:

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

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

最佳答案

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

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

返回:

england
sweden

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.

All together:

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"

关于bash - 使用冒号分隔的字符串遍历文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26994461/

相关文章:

linux - 在文件中每第 n 次出现字符时插入内容

linux - 如何通过awk命令将以>开头的行替换为同一行的第15列?

linux - 有没有办法在 bash 脚本中的 awk 语句中定义用户定义的函数?

awk - 删除除 2 个匹配模式 Shell 脚本之间的文本之外的所有文本

python - 如何使用 python subprocess.call,将 stdout 的副本发送到日志文件,同时检测第一个命令的结果

arrays - 在 AWK 中使用 Bash 数组

python 循环提取 API 数据以迭代 URL

php - 我的代码只向我显示第一个结果并带来另一个空值

javascript - 清除内容后图像不会显示

linux - stty:标准输入:使用 pdsh 或 ssh 时参数无效