首页 > 解决方案 > 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

标签: bashshell

解决方案


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.


推荐阅读