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
2
  • Please paste your script first at shellcheck.net and try to implement the recommendations made there. Commented Nov 15, 2020 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: stackoverflow.com/questions/16623835/… Commented Nov 15, 2020 at 20:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

As you say, the extension is known, use the ${file%.txt} form to strip it off, instead of relying on basename.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.