1

I have a file (ordered_names) which is in the format

pub 000.html
pub.19 001.html

for about 300 lines, And I can't find a way to feed this to the mv command.

I have read Provide strings stored in a file as a list of arguments to a command?, but I could not get what I came for.

Here are some of the attempts I made :

for line in "$(cat ../ordered_files.reversed)"; do mv  $(echo "$line"); done
for line in "$(cat ../ordered_files.reversed)"; do echo mv $(echo $line | cut -d' ' -f 1) $(echo $line | cut -d' ' -f 2) ; done
  • This is [BashFAQ 001](http://mywiki.wooledge.org/BashFAQ/001). See also [Why is looping over find's output bad practice?](https://unix.stackexchange.com/questions/321697/why-is-looping-over-finds-output-bad-practice). The basic problem is the same, but of course `find -exec` doesn't work with cat. – ilkkachu Dec 16 '17 at 13:37

1 Answers1

3

Try:

while read -r file1 file2; do mv -n -- "$file1" "$file2"; done <inputfile

This assumes that the file names on each line in the input file are space-separated. This, of course, only works if the file names themselves do not contain spaces. If they do, then you need a different input format.

How it works

  • while read -r file1 file2; do

    This starts a while loop. The loop continues as long as input is available. For each line of input, two parameters are read: file1 and file2.

  • mv -n -- "$file1" "$file2"

    This moves file1 to file2.

    The option -n protects you from overwriting any file at the destination. Of course, if it is your intention to overwrite files, remove this option.

    The string -- signals the end of the options. This protects you from problems should any of the file names start with a -.

  • done

    This signals the end of the while loop.

  • <inputfile

    This tells the while loop to gets its input from a file called inputfile.

John1024
  • 73,527
  • 11
  • 167
  • 163
  • I always recommend using `mv -n` or `mv -i` for bulk moves like this, to avoid accidental overwriting (silent & irreversible) of files due to name conflicts. In this case, `mv -i` would try to read overwrite confirmations from the file list, which wouldn't work well at all, so `mv -n` is the way to go. – Gordon Davisson Dec 16 '17 at 07:24
  • @GordonDavisson Excellent point. I just added `-n` added to the answer. – John1024 Dec 16 '17 at 07:34