Sardonic
Sardonic

Reputation: 471

Unix Shell scripting: how to modify output file names accordingly

So my current shell scripting is:

for j in *.jpg
do
  tesseract $j $j
done

where tesseract converts jpg files into text files. With this script, if there was a file HAHA.jpg, then the output file name becomes, HAHA.jpg.txt but I want it to be just HAHA.txt

Is there a way to make the output file name as HAHA.txt instead of HAHA.jpg.txt?

Upvotes: 0

Views: 998

Answers (3)

perreal
perreal

Reputation: 97928

Using basename:

for j in *.jpg
do
  tesseract $j $(basename -s .jpg $j)
done

Upvotes: 0

Guru
Guru

Reputation: 16974

Add this line after your tesseract command:

for j in *.jpg
do
  tesseract $j $j
  mv ${j}.txt  ${j/jpg/txt}
done

Even though the tesseract has renamed your file, the variable $j will be containing HAHA.jpg.

Upvotes: 0

chris
chris

Reputation: 5018

If you have a shell variable j you can strip a suffix matching a given pattern as follows

${j%%.jpg}

Where %% indicates that the longest matching suffix should be removed and .jpg is the pattern ("a dot, followed by three letters: j, p, and g").

Upvotes: 2

Related Questions