繁体   English   中英

bash shell脚本automaticall添加文件扩展名

[英]bash shell script automaticall add on file extension

您好,所以今天我在玩我的Shell脚本,并想使其变得更加用户友好,所以我将其设为自动添加文件扩展名。

例如,说用户要使用grep搜索文件,但首先他们必须输入文件名,在这种情况下,可以说file.txt我要执行的操作是自动在.txt上添加,因此用户只需要输入在“文件”中

这是我到目前为止所拥有的,但这不起作用:

echo "Current .txt files "
        ls -R |grep .txt
        echo "--------------------------------------------------------------------------------"
                echo -n "Please select a file to search in: "
                read fileName
                file=$fileName.txt

我想在这种情况下,因为我在变量名的末尾附加了扩展名,但这没有用。

用引号引起来:

file="$filename.txt"

编辑:碰巧,这个答案是不正确的。 请参阅下面的评论和其他答案。

您的代码应该可以工作。 见下文-

test.sh内容:

#!/bin/bash

echo "Current .txt files "
        ls -R |grep .txt
        echo "--------------------------------------------------------------------------------"
                echo -n "Please select a file to search in: "
                read fileName
                file=$fileName.txt

echo "You are searching for $file"
ls -l "$file"

测试运行:

$ ./test.sh
Current .txt files
p1.txt
t1.txt
t2.txt
--------------------------------------------------------------------------------
Please select a file to search in: t2
You are searching for t2.txt
-rw-r----- 1 d1rld1f1 d1rld1f1 4 Apr 20 12:41 t2.txt
$

顺便说一句,通常建议将变量名称用双引号引起来。 这样可以防止重新解释带引号的字符串中的所有特殊字符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM