1

I saw this post but it didn't help me (I couldn't figure how to add "" and add to the existing string).

I'm trying to create a script that combines all mp3 files in a directory into one file using the "cat" command and give the new file the name of the directory its in.

RES
dirName=${PWD##*/}
for entry in *.mp3; do
    RES="${RES} ${entry}"

done

#echo "$foo"
cat ${RES} > ${dirName}

Since the file names have spaces I get the following error

cat: 01: No such file or directory
cat: רצועה: No such file or directory
cat: 1.mp3: No such file or directory
cat: 02: No such file or directory


Thanks

אVי
  • 1,913
  • 6
  • 22
  • 35
  • 1
    You'd have to use an array to do this properly, which isn't supported by POSIX sh. You don't need an intermediate variable at all, though: `cat *.mp3` does the trick. `dirName` is a directory, by the way, so you can't use it as the output file. – Benjamin W. Jul 13 '20 at 18:39

1 Answers1

2

Use an array rather than a string.

res=()
for entry in *.mp3; do
    res+=("$entry")
done

cat "${res[@]}" > "$dirName/combined.mp3"

Of course, this is really unnecessary. Unless you need to do more manipulations in the loop you can just pass the wildcard to cat directly:

cat *.mp3 > "$dirName/combined.mp3"
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • You don't even need the loop here. `res=(*.mp3)`. – chepner Jul 13 '20 at 18:52
  • 1
    @chepner True. But this generalizes better, in case some manipulation of `$entry` needs to be done. – Barmar Jul 13 '20 at 18:53
  • @Barmar: Why do we need a variable here? We could simply do a `cat *.mp3 >output.mp3`. Wordsplitting is done before filename expansion. – user1934428 Jul 14 '20 at 04:59
  • @user1934428 As I said above, this is more general. You an modify `$entry` in the loop if necessary. – Barmar Jul 14 '20 at 05:43
  • You can, but if you modify `entry`, the resulting file most likely won't exixt in the current directory, and the `cat` would fail. Note that that OP's problem was to catenate together all MP3 files in his directory, producing a combined one in a different directory. Danger is that the OP would use your approach for his task (which of course **does** produce the correct outcome), and then think this would be the normal way to do it. I would at least also post the approach you also would use when having to implement this task. – user1934428 Jul 14 '20 at 07:31