Remove extension in loop

Dear all
sorry for bothering you wityh dumb question but I am stucked with an issue.
Well, I am trying to loop over files in folder, make an operation and rewrite the output.
Example:

INPUT

file1.txt
file2.txt
file3.txt

My command (doesn't work!!)

for file in /path/to/*.txt
do command -input $file -output "${file%.*}"_sorted.txt
done

OUTPUT(desired!)

file1_sorted.txt
file2_sorted.txt
file3_sorted.txt

Any suggestion?

Best

Giuliano

In what way does it "doesn't work"? What do you actually get? The substitution appears to work here, in the BASH shell.

Yes sorry for misunderstanding..

Input

file1.txt
file2.txt
file3.txt

My command (doesn't work!!)

for file in /path/to/*.txt
do command -input $file -output "${file%.*}"_sorted.txt
done

My output

file1.txt_sorted.txt
file2.txt_sorted.txt
file3.txt_sorted.txt

desired output

file1_sorted.txt
file2_sorted.txt
file3_sorted.txt

What is your shell? What version, too?

/bin/bash
3.2.57(1)-release

Try ${file/.txt/}

no it doesn't work. It doesn't recognize the pattern.

Are you sure that it's interpreted by bash ? Or is it part of a script that has a #!sh shebang?

A shell that does not understand this would throw an error.
--
In case you have two or more extensions, e.g. file1.txt.txt , then you get

echo ${file%.*}
file1.txt

Perhaps you need

echo ${file%%.*}
file1

Sorry all my shell is

#!sh

Thanks made in Germany but your suggestion doesn't work!

Please run the script with the -x option set and post the output.

Really sorry guys the solution of MadeinGermany works fine...I had a my mistake!

Sorry for annoying you!

Thanks

Giuliano

1 Like

No trouble, though I'm left curious what the issue was :slight_smile:

my fault..

Usage is

command [options] <input> <ouput.prefix>

my command for this site was was

for file in /path/to/*.txt
do command -input $file -output "${file%.*}"_sorted.txt
done

My real command was

for file in /path/to/*.txt
do command $file -o "${file%.*}"_sorted.txt
done

That was because I though was more clear specify INPUT and OUTPUT for you.
BUT
My mistake was to think that

-o

was

output 

when instead is

final output to stdout

well that was do not know how it matter..
hope that my awful explanation is clear.. better I go home now!

still sorry for my mistake next time i'll read carefully the options!

best

1 Like