bash - editing the name of a variable in bash
问题描述
So basically i have a program that searches each file in a directory and creates a variable which consists of the name of the file and a number. The problem is that instead of creating the variable with the file's name and the number it also includes the extension of the file which i dont want.
Expected output:
./my_script.sh inputs outputs 1
InputFile=test1 NumThreads=1
OutputFile=test1-1.txt
My output:
./my_script.sh inputs outputs 1
InputFile=inputs/test1.txt NumThreads=1
OutputFile=inputs/test1.txt-1.txt
Program:
#!/bin/bash
Word1="${1}"
Word2="${2}"
Num="${3}"
for file in $(ls ${Word1}/*.txt)
do
for i in $(seq 1 ${Num})
do
echo "InputFile="${file} "NumThreads="${i}
out="${file}-${Num}".txt
echo "OutputFile="${out}
done
done
解决方案
Since you already know the file extension, you can extract the filebase directly using basename as follow:
filebase=$(basename -- "$file" .txt)
and then return
out="${filebase}-${Num}".txt
If you don't know the extension, you can extract it first like that:
extension=".${file##*.}"
So you can extract the filebase in one line as follows:
filebase=$(basename -- "$file" .${file##*.})
You can check out this answer for ways to extract the different path parts.
The mysterious ${}
syntax which allows you to modify a variable is called shell parameter extensions.
推荐阅读
- c++ - 矢量打印地址
的元素显示垃圾 - ios - 在 xcode 10 中找不到架构 x86_64 的符号
- gradle - Gradle 运行 webpack 任务但没有效果
- ios - 在 Xcode 升级后 Flutter iOS 构建失败错误并带有多个命令
- angular - 如何从不同的组件加载 Nebular Angular 6 中的菜单?
- r - R中的ggplot2不会在pdf中生成1000多个图
- java - 如何使用 BorderLayout 缩小我的文本字段并在右下角定位标签?
- components - weka的主成分分析返回错误的实例
- mysql - 使用星号(通配符)运算符执行搜索时,MySQL 将如何使用 FT 索引?
- visual-studio - Visual Studio 表单设计