【问题标题】:linux shell script: getting filename from a user input stringlinux shell脚本:从用户输入字符串中获取文件名
【发布时间】:2012-03-10 18:50:17
【问题描述】:

我想编写一个 shell 脚本,在其中我将从用户那里获取一行输入,其中将包含一些 xxx.cpp 作为文件名。 我想在另一个变量中得到那个“xxx”。 例如

如果用户输入为:

some params path/to/file/xyz.cpp more p/ara/ms

我想得到出现在“.cpp”之前和最后一次出现在“.cpp”之前的“/”之后的xyz

【问题讨论】:

  • 如果输入是 "cp/b.cpp/a.cpp.f.cpp/ foo.cpp cpp/cpp.cpp/b.cpp" 你需要澄清你的要求.
  • 这不会发生.. 用户只会给出一个 ***.cpp 文件名

标签: linux string shell scripting substring


【解决方案1】:

使用basename [param] [.ext]

echo `basename $1 .cpp`

其中 1 是 path/to/file.xyz 在参数列表中的索引。

【讨论】:

  • 我不明白“索引”的含义..?如果我将输入输入为:[ some params path/to/file/xyz.cpp more p/ara/ms ] 索引将是什么以及如何获取它?
  • @NDThokare,如果是完整的命令行,其中一些是要运行的程序,则some 的索引为 0,params 的索引为 1,path/to/file/xyz.cpp 的索引为2.
【解决方案2】:

这是一个示例 bash 脚本,用于提示用户输入文件列表并过滤所有输入并仅显示以“.cpp”结尾(已删除 .cpp)且可读的文件的基本名称

#!/bin/bash
echo Enter list of files:
read list_of_files
for file in $(echo $list_of_files); do
    if echo $file | grep '\.cpp$' > /dev/null; then
        if [[ -r $file ]]; then
            fn=$(basename ${file})
            fn=${fn%.*}
            echo $fn
        fi
    fi
done

【讨论】:

  • 如果我运行这个脚本,它不会在命令行接受任何输入。我想读取用户的输入并用它来提取文件名。
  • 好的,我修复了它,所以它会提示您输入而不是使用脚本的参数
猜你喜欢
  • 2012-12-28
  • 2013-11-13
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 2018-05-03
  • 2018-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多