1

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
Martim Correia
  • 483
  • 5
  • 16
  • Please paste your script first at [shellcheck.net](http://www.shellcheck.net/) and try to implement the recommendations made there. – Cyrus Nov 15 '20 at 20:56
  • I am not sure If I got you problem. For what ist Word2? Maybe this link helps to cut parts of your output: https://stackoverflow.com/questions/16623835/remove-a-fixed-prefix-suffix-from-a-string-in-bash – Maik Nov 15 '20 at 20:56

1 Answers1

3

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.

e-malito
  • 878
  • 1
  • 7
  • 14