Home > Software design >  passing file names with spaces to imagemagic convert
passing file names with spaces to imagemagic convert

Time:11-07

Say I have the following files:

'CamScanner 11-06-2022 13.04.24_1.jpg'   'CamScanner 11-06-2022 13.04.24_20.jpg'
'CamScanner 11-06-2022 13.04.24_10.jpg'  'CamScanner 11-06-2022 13.04.24_21.jpg'
'CamScanner 11-06-2022 13.04.24_11.jpg'  'CamScanner 11-06-2022 13.04.24_22.jpg'
'CamScanner 11-06-2022 13.04.24_12.jpg'  'CamScanner 11-06-2022 13.04.24_23.jpg'
'CamScanner 11-06-2022 13.04.24_13.jpg'  'CamScanner 11-06-2022 13.04.24_24.jpg'
'CamScanner 11-06-2022 13.04.24_14.jpg'  'CamScanner 11-06-2022 13.04.24_3.jpg'
'CamScanner 11-06-2022 13.04.24_15.jpg'  'CamScanner 11-06-2022 13.04.24_4.jpg'
'CamScanner 11-06-2022 13.04.24_16.jpg'  'CamScanner 11-06-2022 13.04.24_5.jpg'
'CamScanner 11-06-2022 13.04.24_17.jpg'  'CamScanner 11-06-2022 13.04.24_6.jpg'
'CamScanner 11-06-2022 13.04.24_18.jpg'  'CamScanner 11-06-2022 13.04.24_7.jpg'
'CamScanner 11-06-2022 13.04.24_19.jpg'  'CamScanner 11-06-2022 13.04.24_8.jpg'
'CamScanner 11-06-2022 13.04.24_2.jpg'   'CamScanner 11-06-2022 13.04.24_9.jpg'

I would like to convert these files to a pdf. The files aren't currently listed in version order, so this is what I tried:

convert $(ls -v) output.pdf

But this fails due to the spaces in the file names. I would like to pass the file names to convert listed in version order, as well as handle the spaces inside the names. I have seen some SO questions where they sort the files in some order before passing it to convert, but none of those contained any spaces in the file names. Any suggestions would be appreciated :)

Edit: I have also tried:

ls -v | xargs -I% convert % output.pdf

But this only converts a single jpg to pdf.

CodePudding user response:

You need to quote each file name. Or, try this.

readlines filearray <(ls -v)
convert "${filearray[@]}" output.pdf

A much better solution would use machine-readable dates and zero-padded sequence numbers in the file names, which would make them unambiguous to human readers and solve the sort order problem trivially.

for file in CamScanner\ ??-??-????\ ??.??.??_*.jpg; do
    tail=${file##*_}
    printf -v idx i ${tail%.jpg}
    mv "$file" "CamScanner-${file:17:4}-${file:14:2}-${file:11:2}_${file:22:8}_$idx.jpg"
done

Demo, of sorts: https://ideone.com/Svl6uQ

  • Related