简体   繁体   English

阅读文本文件 - bash

[英]reading text file - bash

I am trying to read a text file-"info.txt" which contains the following information 我正在尝试阅读包含以下信息的文本文件“info.txt”

info.txt info.txt

1,john,23
2,mary,21

what I want to do is to store each columns into a variable and print any one of the columns out. 我想要做的是将每列存储到一个变量中并打印出任何一列。

I know this may seems simple to you guys but I am new to writing bash script, I only know how to read the file but I don't know how to delimit the , away and need help. 我知道这对你们来说似乎很简单,但我是新手写的bash脚本,我只知道如何阅读文件,但我不知道如何划分,离开并需要帮助。 Thanks. 谢谢。

while read -r columnOne columnTwo columnThree
do 
echo  $columnOne
done < "info.txt"

output 产量

1,
2,

expected output 预期产出

1
2

You need to set the record separator: 您需要设置记录分隔符:

while IFS=, read -r columnOne columnTwo columnThree
do 
echo "$columnOne"
done < info.txt

Is good to check if the file exists too. 最好检查文件是否也存在。

#!/bin/bash
INPUT=./info.txt
OLDIFS=$IFS
IFS=,
[ ! -f $INPUT ] && { echo "$INPUT file not found"; exit 99; }
while read -r columnOne columnTwo columnThree
do 
    echo "columnOne : $columnOne"
    echo "columnTwo : $columnTwo"
    echo "columnThree : $columnThree"
done < $INPUT
IFS=$OLDIFS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM