如何使用Shell脚本遍历每行具有多个单词的文本文件? [英] How to iterate over text file having multiple-words-per-line using shell script?
本文介绍了如何使用Shell脚本遍历每行具有多个单词的文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当文本文件具有以下内容时,我知道如何遍历文本行:
I know how to iterate over lines of text when the text file has contents as below:
abc
pqr
xyz
但是,如果我的文本文件的内容如下所示,
However, what if the contents of my text file are as below,
abc xyz
cdf pqr
lmn rst
,我需要将值"abc"存储到一个变量中并将"xyz"值存储到另一个变量中.我该怎么办?
and I need to get values "abc" stored to one variable and"xyz" stored to another variable. How would I do that?
推荐答案
如果定界符是空格,则可以执行以下操作:
If the delimiter is a space then you can do:
#!/bin/bash
ALLVALUES=()
while read line
do
ALLVALUES+=( $line )
done < "/path/to/your/file"
因此,之后,您只需引用 $ {ALLVALUES [0]}
或 $ {ALLVALUES [1]}
等
So after, you can just reference an element by ${ALLVALUES[0]}
or ${ALLVALUES[1]}
etc
这篇关于如何使用Shell脚本遍历每行具有多个单词的文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文