1

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

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

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: Text file busy。问题不在提供的文件或文件夹变量或路径中,它只是没有将值传递给变量这边走

4

2 回答 2

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
于 2013-10-02T21:11:51.423 回答
1

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

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"

测试OK/etc/passwd

于 2013-10-02T21:12:04.853 回答