如何将文本文件的内容放入变量?

时间:2013-10-02 21:07:29

标签: bash

我知道有类似的问题,我首先在那里搜索答案,但无法使代码工作。

这个想法是 - 用户输入文件夹的名称,而不是该文件夹中文件的名称,程序应该将文件内容放入变量。

echo " Type name of the folder where you want to edit file "
read folder
echo " Type name of the file you want to edit "
read file
#cont=$(cat "$folder"/"$file")
#cont=$(cat test/test1.txt)//its the name of existing variable and file so should work
cont=`cat test/test1.txt`
echo "$cont"

我尝试了不同的解决方案,但它们仅适用于当前目录中的文件。 也许有人对正确的语法或可能的解决方案有任何想法。 提前谢谢!

我试过cont = cat“$ folder”/“$ file”我写的是test / test1.txt:文件文件很忙。问题不在文件或文件夹变量或提供的路径中,它只是没有传递值以这种方式改变它

2 个答案:

答案 0 :(得分:1)

您不需要echo $(cat...)。这是对echo的无用使用。只需cat即可。

#!/bin/sh

echo " Type name of the folder where you want to edit file "
read folder
echo " Type name of the file you want to edit "
read file
var=$(cat "$folder"/"$file")
echo "$var"

结果:

$] ./test.sh
Type name of the folder where you want to edit file 
test1
Type name of the file you want to edit 
table
cat
dog

如果在给出输入文件夹的完整路径的同时从另一个目录执行,这也有效。

$] ./path/to/test.sh
Type name of the folder where you want to edit file 
/path/to/folder
Type name of the file you want to edit
table
cat
dog

答案 1 :(得分:1)

我怀疑你有一个shell环境问题(你cont=$(cat "$folder"/"$file")的第一次尝试应该有效),尝试使用另一个环境:

exec bash

然后

read -p "Type name of the folder where you want to edit file >>> " dir
read -p " Type name of the file you want to edit >>> " file

cont="$(< "$dir/$file")"

echo "$cont"

使用/etc/passwd

进行了测试
相关问题