【问题标题】:Read a file using a bash script使用 bash 脚本读取文件
【发布时间】:2019-01-31 17:31:30
【问题描述】:

我需要使用“Do/While”循环读取文件。
如何将内容读取为字符串?

这是我的代码:

cat directory/scripts/tv2dbarray.txt | while read line
do
  echo "a line: $line"
done

错误:

test.sh: line 4: syntax error near unexpected token `done'
test.sh: line 4: `done'

【问题讨论】:

  • 这段代码没有问题。脚本中还有其他内容吗?也许是另一个whileif 或不平衡的引号、大括号、方括号或圆括号?

标签: bash


【解决方案1】:

这里没有理由使用cat ——它没有添加任何功能并且产生了一个不必要的过程。

while IFS= read -r line; do
  echo "a line: $line"
done < file

要将文件的内容读入变量,请使用

foo=$(<file)

(请注意,这会修剪尾随的换行符)。

【讨论】:

  • 我希望我能多次投票并确保它是每次 Google 搜索的最佳结果。在过去的一个小时里,我以多种方式表达了这个问题,直到现在我每次都找到了“使用猫”的答案。最后,理智的单行答案(与 cat 不同,它简单有效。)
  • 感谢您的编辑,@gniourf_gniourf -- 你每天都会学到新东西!
【解决方案2】:
cat file | while read line
do
  echo "a line: $line"
done

编辑:

要将文件内容放入 var 中,请使用:

foo="`cat file`"

【讨论】:

【解决方案3】:

这应该可行:

file=path/of/file/location/filename.txt

while IFS= read -r varname; do
    printf '%s\n' "$varname"
done < "$file"

【讨论】:

    【解决方案4】:

    试试看

    while read p
    do 
    echo $p
    done <  directory/scripts/tv2dbarray.txt
    

    【讨论】:

      猜你喜欢
      • 2014-10-26
      • 1970-01-01
      • 1970-01-01
      • 2022-05-30
      • 2014-10-28
      • 2010-12-30
      • 2019-08-03
      • 1970-01-01
      • 2020-06-18
      相关资源
      最近更新 更多