X00145570
X00145570

Reputation: 57

Trying to create a folder and cp the file using text file

I'm trying to create a folder using txt file and copy the file. I have two file types:

try.txt

Changes/EMAIL/header-20-percent-off.gif
Changes/EMAIL/header-50-percent-off.gif

demo of folder named zip2

 zip2/EMAIL/header-20-percent-off.gif
 zip2/EMAIL/header-50-percent-off.gif

Code:

mkdir -p dirname `xargs -a try.txt`
cp -R  {Dont know how this will work :( }

Actual output:

Changes/EMAIL/header-20-percent-off.gif/
             /header-50-percent-off.gif/

Expected output:

Changes/EMAIL/header-20-percent-off.gif
             /header-50-percent-off.gif

As you can see for some reason it thinks header-20-percent-off.gif and header-50-percent-off.gif are directories.

Once Changes/Email/ is created I would like to copy the two gif files header-20-percent-off.gif and header-50-percent-off.gif there.

Upvotes: 0

Views: 70

Answers (1)

KamilCuk
KamilCuk

Reputation: 142025

First create folders:

<try.txt xargs -d$'\n' dirname | xargs -d$'\n' mkdir -p

Then copy files. First prepare the stream with proper source and destination directories with sed and then pass to xargs:

sed 's@^Changes/\(.*\)@zip2/\1\n&@' try.txt |
xargs -d$'\n' -n2 cp

But if you are not proficient in bash, just read the stream line by line:

while IFS= read -r dest; do
   dir=$(dirname "$dest")
   mkdir -p "$dir"
   src=$(sed 's@^Changes@zip2@' <<<"$dest")
   cp "$src" "$dest"
done < try.txt

Don't use backticks `, they are highly discouraged. Use $(...) for command substitution instead.

Just doing xargs -a try.txt without a command makes little sense, just $(cat try.txt) or better $(<try.txt).

Use -t option with xargs to see what is it doing.

Explicitly specify the delimeter with xargs -d$'\n' - otherwise xargs will parse " ' and \ specially.

I believe with some luck and work you could just use rsync with something along rsync --include-from=try.txt changes/ zip2/.

Upvotes: 1

Related Questions