linux - 有没有办法读取文本文件并使用其中的单词作为输入?

标签 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

最佳答案

您快完成了。请注意,您可以使用 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 个字段

关于linux - 有没有办法读取文本文件并使用其中的单词作为输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56250881/

相关文章:

python scrapy shell 异常 : address "' http:"not found: [Errno 11001] getaddrinfo failed

linux - 将多行日志文件转换为 CSV

linux - 目标有一个依赖项,该依赖项本身不是目标

linux - 将带空格的字符串作为参数传递给函数

linux - Linux环境下Oracle External Tables字段解析

linux - for 循环中 if 语句中的 if 语句

bash - 在heredoc中禁用命令替换?

c++ - 在 Linux 中发送空的 Socket 缓冲区?

bash - 使用 bash 递归合并 yaml 配置文件

linux - 语法错误 : "(" unexpected when sh a file