Вопрос

I have a folder containing images and textfiles. The image name is in this order: tramnummerx.JPG The text file is in this order : tramnummerx.txt

to be clear: x is a variable number

Inside the .txt is a 4 digit number, for example 6303. In this case I would like to rename the .JPG file to : tramnummerx-6303.JPG

In my current script I did this:

x=O
extention='*.txt'
for i in 'ls $extention'
do
x = 'expr $x + 1'
y= ??? the command for extracting the number ???
mv tramnummerx.JPG tramnummerx-$y.JPG
done

I tried some things like awk '{print $(NF-1), $NF;}' filename for "y=" but I just ended up deleting my files this way.

Thanks in advance!

SOLUTION:

for i in 'ls $extention'
do
x='expr $x +1'
read y < tramnummer$x.txt
mv tramnummer$x.JPG tramnummer$x-$y.JPG
done
Это было полезно?

Решение

Use regular expression matching to extract the number from the image file name, and read to extract the new number from the corresponding text file. (Some details may need adjusting if I misunderstood your question, but the general approach will stay the same.)

for img in *.JPG; do
    [[ $img =~ tramnummer([[:digit:]]+).JPG ]]
    x=${BASH_REMATCH[1]}
    read y < tramnummer$x.txt
    mv tramnummer$x.JPG tramnummer$x-$y.JPG
done

In your existing code, you could use lines like

x=$(( x + 1 ))
y=$(< tramnummer$x.txt )

but the proposed solution is a little cleaner and more idiomatic.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top