Discussion:
[Help-bash] copy files w
Val Krem
2017-04-30 00:36:15 UTC
Permalink
Hi all,

I have several files with the same extension name(*.txt). I want to have copy of these files by attaching a suffix to each of the files. Example test1.txt should be copied to test1_new.txt. The suffix to be added in all files is the same. I tried using this but did not work.

ls *.txt | xargs -I {} cp {} {}_new.txt

test.txt should be test_new.txt
but I got test.txt_new.txt

what should I do to make work?

Thank you in advance
Chris F.A. Johnson
2017-04-30 01:07:56 UTC
Permalink
Post by Val Krem
Hi all,
I have several files with the same extension name(*.txt). I want to have copy of these files by attaching a suffix to each of the files. Example test1.txt should be copied to test1_new.txt. The suffix to be added in all files is the same. I tried using this but did not work.
ls *.txt | xargs -I {} cp {} {}_new.txt
test.txt should be test_new.txt
but I got test.txt_new.txt
what should I do to make work?
for file in *.txt
do
cp "$file" "${file/.txt/_new.txt}"
done
--
Chris F.A. Johnson, <http://cfajohnson.com>
Val Krem
2017-05-25 21:41:08 UTC
Permalink
Thank you so much Greg!


The original question was that if the file is say
"Atest.txt" then I want copy it to

"Atest_new.txt"

and I got it by tweaking your script!
I am trying to modify this script to do it recursively. I want to go in all sub folders and copy the files and here is my attempt
Copy them where?
find . -type f -name *.txt | for file in *.txt
do
cp "$file" "${file/.txt/_new.txt}"
done
But it only do the job in the current directory.
You want to copy each file to a new file in the *same directory* with
_new inserted before .txt?

find . -type f -name '*.txt' -exec sh -c '
for f; do cp "$f" "${f%.txt}_new.txt"; done

' x {} +

Purists will insist that I remove the ; after "for f". Decide how pure
you wish to be.

You have at least two fundamental mistakes in yours:

1) Unquoted *.txt glob expands to files in $PWD instead of letting find
expand it.

2) You pipe find's output to a loop that does not read it, and which
then merrily proceeds to do its own *second* nonrecursive glob
expansion.
Eduardo Bustamante
2017-05-25 20:32:42 UTC
Permalink
On Thu, May 25, 2017 at 3:25 PM, Val Krem <***@yahoo.com> wrote:
[...]
find . -type f -name *.txt | for file in *.txt
do
cp "$file" "${file/.txt/_new.txt}"
done
The for loop doesn't care about the output of find. For that you'll
need to pipe find's output to something that does read from the pipe
(while read), or instead of find use bash's globstar, i.e. for file in
./**/*.txt

Loading...