【问题标题】:Is there any way to read text file and use words inside it as input?有没有办法读取文本文件并使用其中的单词作为输入?
【发布时间】:2019-05-23 14:21:36
【问题描述】:

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

【问题讨论】:

  • 请将您的所有代码/示例包装在 CODE TAGS 中。
  • 你能详细说明一下我对这个世界很陌生吗?
  • 请看这篇文章以供参考meta.stackexchange.com/questions/51144/…
  • @SKuser :您还应该定义什么是单词。例如,abc,defx100 分别是一个词还是两个词?
  • @SKuser : 用fmt -1 content.txt 替换cat content.txt 怎么样?

标签: linux bash shell centos


【解决方案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 个字段

【讨论】:

  • 请引用您的字符串。也许有一天你会读到$(rm *) 中的一个变量*
  • @WalterA : rm 不会造成伤害,因为 echo 仍然不会执行代码。 * 参数有效。我已经相应地更新了我的答案。由于我通常使用 Zsh,所以我总是忘记在执行 bash 时需要大量引用。我不太喜欢 bash 的原因之一。
  • @user1934428 你能帮我解决我的另一个问题吗?请查看我的个人资料
猜你喜欢
  • 1970-01-01
  • 2022-10-07
  • 2013-12-30
  • 1970-01-01
  • 1970-01-01
  • 2022-11-30
  • 2022-08-04
  • 1970-01-01
  • 2019-04-27
相关资源
最近更新 更多