![](/img/trans.png)
[英]Reading the contents of a text file and assign to a variable using bash script
[英]Need to assign the contents of a text file to a variable in a bash script
我对制作 bash 脚本非常陌生,但我的目标是获取一个我拥有的 .txt 文件并将 txt 文件中的单词字符串分配给一个变量。 我已经尝试过了(不知道我是否在正确的轨道上)。
#!/bin/bash
FILE="answer.txt"
file1="cat answer.txt"
print $file1
当我运行这个时,我得到
Warning: unknown mime-type for "cat" -- using "application/octet-stream"
Error: no such file "cat"
Error: no "print" mailcap rules found for type "text/plain"
我能做些什么来完成这项工作?
编辑** 当我将其更改为:
#!/bin/bash
FILE="answer.txt"
file1=$(cat answer.txt)
print $file1
我得到了这个:
Warning: unknown mime-type for "This" -- using "application/octet-stream"
Warning: unknown mime-type for "text" -- using "application/octet-stream"
Warning: unknown mime-type for "string" -- using "application/octet-stream"
Warning: unknown mime-type for "should" -- using "application/octet-stream"
Warning: unknown mime-type for "be" -- using "application/octet-stream"
Warning: unknown mime-type for "a" -- using "application/octet-stream"
Warning: unknown mime-type for "varible." -- using "application/octet-stream"
Error: no such file "This"
Error: no such file "text"
Error: no such file "string"
Error: no such file "should"
Error: no such file "be"
Error: no such file "a"
Error: no such file "varible."
当我输入 cat answer.txt 时,它会打印出这个文本字符串应该是一个变量,但是,我仍然无法让 bash 用这个变量来做到这一点。
您需要反引号来捕获命令的输出(并且您可能需要echo
而不是print
):
file1=`cat answer.txt`
echo $file1
$()
构造从命令返回stdout
。
file_contents=$(cat answer.txt)
谨慎使用命令替换,因为它会删除使变量和输入文件不相同的尾随新行,例如:
$ printf 'a\n\n' > input.txt
$ md5 < input.txt
94364860a0452ac23f3dac45f0091d81
$ x=$(cat input.txt)
$ printf %s "$x" | md5
0cc175b9c0f1b6a831c399e269772661
$ printf %s "$x" | od -ta
0000000 a
0000001
要使文件和变量相同,请添加一个额外的字节,然后稍后将其删除:
$ x=$(cat input.txt && echo .)
$ x=${x%.}
$ printf %s "$x" | md5
94364860a0452ac23f3dac45f0091d81
$ printf %s "$x" | od -ta
0000000 a nl nl
0000003
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.