0

I'm trying to use the variable $y in this snippet below but keep running into the filename showing up as $y.pdf

ls -v *.jpg | tr '\n' ' ' | sed 's/$/\ $y.pdf/' | xargs convert

I've also tried the below:

ls -v *.jpg | tr '\n' ' ' | sed 's/$/\'"$y.pdf"'/' | xargs convert

ls -v *.jpg | tr '\n' ' ' | sed 's/$/\ {$y}.pdf/' | xargs convert

The top one usually fails, as sed is expecting something else. The bottom one just makes my filename {$y}.pdf.

Any ideas for me?

Thanks!

user2416047
  • 100
  • 1
  • 5

1 Answers1

1

Never mind the quoting problem; this is the wrong approach entirely. Just use a for loop to avoid all kinds of potential problems.

for f in *.jpg; do
    convert "$f" "${f%.jpg}.pdf"
done

${f%.jpg} expands to the name of the current file minus the .jpg extension.

To merge the files into one PDF is even simpler (I think):

convert *.jpg "$y.pdf"

Assuming ls -v outputs the file names in the correct order, and there aren't any of the usual concerns with parsing ls involved, use

ls -v *.jpg > input.txt
convert @input.txt "$y.pdf"

(There might be a way to avoid the use of a tempfile, maybe as simple as ls -v *.jpg | convert @- "$y.pdf", but I'm too lazy to figure out all the ways convert can be called.)

chepner
  • 497,756
  • 71
  • 530
  • 681
  • I'm fairly certain I don't want this, only because I want to combine multiple .jpg files into ONE PDF, not each .jpg into a pdf. – user2416047 Jul 21 '16 at 16:04
  • To update on chepner's edit, it isn't this simple unfortunately. Maybe there could be a better way, though. In a nutshell I am combining multiple jpg's into one single PDF. The problem here is I have about ~10,000 files. Each named date-page 1, date-page 2, etc. The problem is that for some reason it isn't merging them properly as it's going Page 1, Page 10, Page 2, Page 20, etc. This is why I'm using ls -v. I searched around and found [this](http://stackoverflow.com/questions/8955425/how-can-i-convert-a-series-of-images-to-a-pdf-from-the-command-line-on-linux#comment32682437_8955465). – user2416047 Jul 21 '16 at 16:10
  • And on his third edit... that actually worked. I think what I did before was convert input.txt file.pdf which tried to convert input.txt into a pdf. I guess I was missing the @. Thanks! – user2416047 Jul 21 '16 at 16:30
  • A sidenote as to why the ordering is so weird: ls outputs them in this way, you could say, that it outputs the files after sorting them alphabetically (1 comes before 2, thus first comes everything with a 1 at the beginning (1, 10, 11, ...). – redxef Jul 21 '16 at 19:02