有什么方法可以读取文本文件并将其中的单词用作输入?

时间:2019-05-22 06:50:39

标签: linux bash shell centos

我正在处理一项任务,我必须阅读文本文件并将其中包含的每个单词作为输入,而且重要的是我必须使用while或任何其他循环来进行处理(不使用awk命令)

我用while循环尝试了它读取文件,但是我无法弄清楚下一步。

以下是详细信息:

内容文件(源文件)

[root@localhost ~]# cat content.txt
Rantndeep,old spice,100,20
D-mart,toothbrush,30,20
more,sack,300,10

必需的输出

[root@localhost ~]# sh parser.sh
Today I went to Rantndeep Store bought old spice For Rs. 100 And paid 20 Rs.as a parking charges
Today I went to D-mart Store bought toothbrush For Rs. 30 And paid 20 Rs.as a parking charges
Today I went to more Store bought sack For Rs. 300 And paid 10 Rs.as a parking charges

我的脚本

[root@localhost ~]# cat p.sh
#/bin/bash
cat content.txt | while read a
do
     echo $a
done

这仅打印上述文件的内容,我想使用任何循环对其进行脚本编写,以便获得输出为

[root@localhost ~]# sh parser.sh
Today I went to Rantndeep Store bought old spice For Rs. 100 And paid 20 Rs.as a parking charges
Today I went to D-mart Store bought toothbrush For Rs. 30 And paid 20 Rs.as a parking charges
Today I went to more Store bought sack For Rs. 300 And paid 10 Rs.as a parking charges

1 个答案:

答案 0 :(得分:1)

您快要做到了。请注意,您可以使用read设置多个变量。试试

IFS=, # Because you separate the items using comma instead of space
while read w1 w2 w3 w4
do
  echo "first word: $w1  second word: $w2  last word: $w4"
done < content.txt

您会看到,在每次迭代中,w1 ... w4包含content.txt中相应行的4个字段