-1

I have movers file with multiply mv commands like

mv /home/foo/oldTest1/user1.txt /home/foo/newTest1/user1.txt
mv /home/foo/oldTest33/user21.txt /home/foo/newTest33/use21.txt
mv /home/foo/oldTest99/user44.txt /home/foo/newTest99/use44.txt

how do I run mv command line by line?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Shco
  • 9
  • 4
  • Does this answer your question? [python, read the filename from directory , use the string in bash script](https://stackoverflow.com/questions/53787850/python-read-the-filename-from-directory-use-the-string-in-bash-script) – etch_45 Dec 13 '20 at 08:00
  • `bash your_file`? – Cyrus Dec 13 '20 at 08:13
  • @etch_45 , I think my issue is more simple I don't call python script from bash – Shco Dec 13 '20 at 08:19
  • @Cyrus , by bash my file name I get mv: cannot move '/home/foo/oldTest1/user1.txt' to '/home/foo/newTest1/user1.txt' : No such file or directory – Shco Dec 13 '20 at 09:12

2 Answers2

0

subrpcoess module can be used to execute bash commands using python. Create a python script run_bash_commands.py as follows :

import sys
import subprocess

def main(input_file):
    with open(input_file,'r',encoding='utf-8')as f:
        command = f.read()
        subprocess.Popen(command, shell=True)

if __name__ == '__main__':
    main(sys.argv[1])

Assuming commands.txt has the mv commands, pass it as argument to the python script.

python run_bash_commands.py commands.txt
Sachin
  • 21
  • 3
  • I think the issue with mv command it not allowed to enter files so the mv command should look like mv /home/foo/oldTest1 /home/foo/newTest1 (without file) – Shco Dec 13 '20 at 11:49
  • any idea how can I remove file name from commands file ? for example every line in commands file the vm command will look like mv /home/foo/oldTest1/user1.txt /home/foo/newTest1/user1.txt will be replace to /home/foo/oldTest1 /home/foo/newTest1 – Shco Dec 13 '20 at 11:55
  • In that case you can read the file line by line using `f.read().splitlines()` which gives you a list of lines like `[line1,line1,line3]`. Iterate through this list and append the command you want to execute. – Sachin Dec 14 '20 at 07:34
0

Assuming:

  • The filepaths do not contain blank characters.
  • The filenames in the directories have ".txt" extension.

Then would you please try:

sed -E 's#/[^/[:blank:]]+\.txt##g' movers_file.txt | bash

The sed command removes filenames from the command lines as you intend to be passed to bash.

Please make sure the mover file is fully under your control not to allow someone else to add an evil code something like: rm -rf /*.

tshiono
  • 21,248
  • 2
  • 14
  • 22