move file by list in file (with leading whitespace)

I have a file that contains file names. For example:

/tmp/list.txt (it is with the spaces at the start of each line):

  /tmp/file.log
  /app/nir/home.txt
  /etc/config.cust

I want, using one line, to move all the files listed in /tmp/list.txt to /app/dest

So it should be something like this:

cat /tmp/list.txt | xargs mv /app/dest/

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You are just missing the -t option for mv (assuming GNU mv):

cat /tmp/list.txt | xargs mv -t /app/dest/

or shorter (inspired by X Tian’s answer):

xargs mv -t /app/dest/ < /tmp/list.txt

the leading (and possible trailing) spaces are removed. Spaces within the filenames will lead to problems.

If you have spaces or tabs or quotes or backslashes in the filenames, assuming GNU xargs you can use:

sed 's/^ *//' < /tmp/list.txt | xargs -d 'n' mv -t /app/dest/

Method 2

Assuming your file names are relatively sane (no newlines or weird characters):

while read file; do mv "$file" /app/dest/; done < list.txt

To deal with weird file names (breaks if a file name has a newline):

while IFS= read -r file; do mv "$file" /app/dest/; done < list.txt

Method 3

for i in $(cat /tmp/list.txt); do mv "$i" /app/dest/; done

Method 4

Pure xargs reading directly from file

xargs -l -i < flist  mv -v {} /app/dst

edit 1 — after @Anthon ‘s comment below,

xargs -I{} < flist  mv -v {} /app/dst

edit 2 — after @John Smith comment below

xargs -I{} < flist mv -v "{}" /app/dst

Quoting replace-str (see man xargs for explanation of replace-str) ensures filenames with blanks are treated as one argument. Newline becomes the input field terminator. However blank lines are ignored.

-I{} Implies the field separator is newline, and implies -L1 (use max one line for each output invocation). So mv is invoked for each input line.

Method 5

mv `cat /tmp/list.txt` /app/dest/

(spaces at start are ignored)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x