wh0watme
wh0watme

Reputation: 3

How to create a script to read a file line by line and concatenate them into a string? (Python or Bash)

I am trying to create a script currently that automates a command multiple times. I have a text file containing links to directories/files that is formatted line by line vertically. An example would be:

mv (X) /home/me

The X variable would change for every line in the directory/file text document. The script would execute the same command but change X each time. How would I got about doing this? Can someone point me in the right direction?

I appreciate the help!

Thanks a bunch!

Upvotes: 0

Views: 314

Answers (3)

KamilCuk
KamilCuk

Reputation: 140960

That's a job for xargs:

xargs -d '\n' -I{} mv {} /path < file

Xargs will read standard input and for each element delimetered by a newline, it will substitute {} part by the readed part and execute mv.

Upvotes: 1

Lars Christian Jensen
Lars Christian Jensen

Reputation: 1632

cat file.txt | while read x; do
  mv "$x" /home/me/
done

Upvotes: 0

Jmonsky
Jmonsky

Reputation: 1519

import os
command = "mv {path} /home/me" # your command example, the {} will be replaced with the path
with open("path_to_file_list.txt", "r") as file:
     paths = [s.strip() for s in file.readlines()] # assuming each line in the file is a path/file of the target files. the .strip() is to clear the newlines

for path in paths:
    os.system(command.format(path=path)) # call each command, replacing the {path} with each file path from the text file.

Upvotes: 0

Related Questions