简体   繁体   English

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

[英]bash shell script automaticall add on file extension

Hello so today i was playing around with my shell script and figured to make it more user friendly i would make it so the file extension of file was automatically added. 您好,所以今天我在玩我的Shell脚本,并想使其变得更加用户友好,所以我将其设为自动添加文件扩展名。

for example say the user wants to search a file using grep but first they must type in thhe name of the file in this case lets say file.txt what i want to do is automatically add on the .txt so the user only needs to type in "file" 例如,说用户要使用grep搜索文件,但首先他们必须输入文件名,在这种情况下,可以说file.txt我要执行的操作是自动在.txt上添加,因此用户只需要输入在“文件”中

here is what i have so far but this does not work: 这是我到目前为止所拥有的,但这不起作用:

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

i thought in this case since i am appending an extension on to the end of the variable name but this has not worked. 我想在这种情况下,因为我在变量名的末尾附加了扩展名,但这没有用。

Put quotes around it: 用引号引起来:

file="$filename.txt"

EDIT: As it happens, this answer is incorrect. 编辑:碰巧,这个答案是不正确的。 See the comments below and the other answer. 请参阅下面的评论和其他答案。

Your code should work. 您的代码应该可以工作。 See below- 见下文-

Contents of test.sh : 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 run: 测试运行:

$ ./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
$

BTW, it is generally advisable to enclose variable names in double quotes. 顺便说一句,通常建议将变量名称用双引号引起来。 This prevents reinterpretation of all special characters within the quoted string. 这样可以防止重新解释带引号的字符串中的所有特殊字符。

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

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