我正在处理一个任务,我必须读取文本文件并将其中的每个单词作为输入,重要的是我必须使用 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/