Copy and rename in the same time (also change filename, not only path):

cp program3.cpp homework6.cpp

Rename only:

mv program3.cpp homework6.cpp
Answer from Cornelius on askubuntu.com
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 59101823 β€Ί copy-and-rename-file-in-linux-bash
copy and rename file in linux bash - Stack Overflow
#!/bin/bash # for each file following the pattern "foo." for i in foo.* do # copy file to "bar" + original extension cp $i bar.${i#foo.} done ... Find the answer to your question by asking. Ask question ... See similar questions with these tags.
🌐
Reddit
reddit.com β€Ί r/bash β€Ί copy and rename file from shell script
r/bash on Reddit: Copy and rename file from shell script
October 26, 2023 -

This is a pretty basic question but I’ve been struggling getting this working for some reason. I am trying to copy a file from one directory to another and renaming it along with the copy. This is being done inside of a shell script, and I have a variable called $filename that stores the NEW file name. Here is the code snippet:

filename="IRcam_fpga_cksm_${checksum}_ver_${version}.pdb"
#filename="This_is_a_file.txt"
echo "filename: ${filename}"
cp ./par/ircam_fpga/designer/impl1/*.pdb output/pl/$filename

The output of the echo command on the console is:

.pdbname: IRcam_fpga_cksm_A415_ver_0x0081

  But the file that gets copied to the new directory does not have the correct name. When I use the version of $filename that is commented out, it works perfectly fine.

Top answer
1 of 5
3
It's hard to tell because the formatting is real messed up You can rename with just: cp /path/to/source/file /path/to/destination/newname
2 of 5
2
The issue you're encountering is because you're overwriting the filename variable after you first set it. When you assign a new value to the filename variable, you essentially lose the previous value, which is why the file is copied with the default This_is_a_file.txt name instead of the intended IRcamfpga_cksm${checksum}ver${version}.pdb. To fix this, make sure that you're not overwriting the filename variable in the script. Here's an updated version of your code: bash filename="IRcamfpga_cksm${checksum}ver${version}.pdb" # Uncomment and use the correct $filename variable without overwriting it echo "filename: ${filename}" # Copy the file and rename it cp ./par/ircam_fpga/designer/impl1/*.pdb output/pl/"${filename}" Explanation: Define the filename correctly: Ensure that the variable filename has the correct value before it's used. Avoid overwriting filename: The second assignment (filename="This_is_a_file.txt") overwrites the first one, which is incorrect. You should either remove or not assign it again. Ensure proper file path: Use "${filename}" to reference the variable safely in the cp command. If checksum and version are being dynamically generated, ensure those variables are correctly populated before being used to build the filename. Here's an example where checksum and version are assumed to be variables with values: bash checksum="A415" version="0x0081" filename="IRcamfpga_cksm${checksum}ver${version}.pdb" echo "filename: ${filename}" # Now copy the file with the correct name cp ./par/ircam_fpga/designer/impl1/*.pdb output/pl/"${filename}" You can try renamer. ai to get easy file renaming solution.
Discussions

linux - How to copy a file to a new file with a new name in same directory but across multiple directories in bash? - Stack Overflow
I am trying to copy an existing file (that is found in across directories) to a new file with a new name in Bash. For example, 'Preview.json' to 'Performance.json'. I have tried using find * -typ... More on stackoverflow.com
🌐 stackoverflow.com
linux - Copying a file from one directory to the next and changing the name - Unix & Linux Stack Exchange
If I wanted to copy a file called myscript from, let's say "/home/myusername" to a directory called "/home/myusername/test" while also renaming it to myscript2... how would I do... More on unix.stackexchange.com
🌐 unix.stackexchange.com
October 19, 2022
shell - How can I copy a file in a bash script and rename it while copying and place it in the same directory - Unix & Linux Stack Exchange
How would I copy a file "file.doc" and rename it while copying to "file_copy.doc" and place it in the same directory ? And this only by calling the script and adding the file name in the argument:... More on unix.stackexchange.com
🌐 unix.stackexchange.com
How to copy and rename files in shell script - Stack Overflow
I have a folder "test" in it there ... .c files with A[1,2..] and copy them to "test" folder. I started like this but I have no idea how to complete it! #!/bin/sh for file in `find test/* -name '*.c'`; do mv $file $*; done ... This code should get you close. I tried to document exactly what I was doing. It does rely on BASH and the GNU ... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 2
3

In an -exec predicate, the symbol {} represents a path that is being considered, starting at one of the starting-point directories designated in the command. Example: start/dir2/Preview.json. You can form other file names by either prepending or appending characters, but whether that makes sense depends on the details. In your case, appending produces commands such as

cp start/dir2/Preview.json start/dir2/Preview.jsonQA

which is a plausible command in the event that start/dir2/Preview.json exists. But cp does not automatically create directories in the destination path, so the result of prepending characters ...

cp start/dir2/Preview.json QAstart/dir2/Preview.json

... is not as likely to be accepted -- it depends on directory QAstart/dir2 existing.

I think what you're actually looking for may be cp commands of the form ...

cp start/dir2/Preview.json start/dir2/QAPreview.json

... but find cannot do this by itself.

For more flexibility in handling the file names discovered by find, pipe its output into another command. If you want to pass them as command-line arguments to another command, then you can interpose the xargs command to achieve that. The command on the receiving end of the pipe can be a shell function or a compound command if you wish.

For example,

# Using ./* instead of * ensures that file names beginning with - will not
# be misinterpreted as options:
find ./* -type f -name 'Preview.json' |
  while IFS= read -r name; do  # Read one line and store it in variable $name
    # the destination name needs to be computed differently if the name
    # contains a / character (the usual case) than if it doesn't:
    case "${name}" in
      */*) cp "${name}" "${name%/*}/QA${name##*/}" ;;
      *)   cp "${name}" "QA${name}" ;;
    esac
  done

Note that that assumes that none of your directory names contain newline characters (the read command would split up newline-containing filenames). That's a reasonably safe assumption, but not absolutely safe.

Of course, you would generally want to have that in a script, not to try to type it on the fly on the command line.

2 of 2
0

If you want to copy Preview.json to a new name like Performance.json, across multiple folders, you can do it like this directly on terminal:

find . -type f -name 'Preview.json' | while read -r file; do \
  dir="${file%/*}"; \
  cp "$file" "$dir/Performance.json"; \
done

This works like finds every Preview.json in subfolders and copies it to Performance.json in the same folder

For example, If you have .....

./project1/Preview.json
./project2/Preview.json

..... You’ll get

./project1/Performance.json
./project2/Performance.json

It’s just Bash string slicing:

${file%/*} = everything before the last slash β†’ folder

${file##*/} = just the filename

Check man bash or Google "bash parameter expansion"

🌐
Ask Ubuntu
askubuntu.com β€Ί questions β€Ί 1205513 β€Ί copy-over-a-large-number-of-files-with-new-names
command line - Copy over a large number of files with new names - Ask Ubuntu
new="$f3""_""$name""_""$mod2"".""$ext" will format the new file name as owner_name_lastmodified.extension and assign it to the variable new so it will contain a value like so: ... cp -p "$oldpath""$f9" "$newpath""$new" will copy the original ...
Find elsewhere
🌐
Network World
networkworld.com β€Ί home β€Ί blogs β€Ί unix as a second language
Copying and renaming files on Linux | Network World
January 23, 2024 - This command will move a file to a different directory, change its name and leave it in place, or do both. $ mv myfile /tmp $ mv myfile notmyfile $ mv myfile /tmp/notmyfile Β· But we now also have the rename command to do some serious renaming for us. The trick to using the rename command is to get used to its syntax, but if you know some perl, you might not find it tricky at all. Here’s a very useful example. Say you wanted to rename the files in a directory to replace all of the uppercase letters with lowercase ones.
🌐
DEV Community
dev.to β€Ί yashsugandh β€Ί how-to-copy-move-and-rename-files-and-directories-in-linux-system-4kpo
How to Copy, Move and Rename Files and Directories in Linux System - DEV Community
May 23, 2020 - Now let's have a look at how to rename a file/directory. ... Yes the mv command is used for both moving as well as renaming a file/directory. ... mv represents move command original represents the current_name original new represents new_name new
🌐
Red Hat
redhat.com β€Ί en β€Ί blog β€Ί move-copy-files-linux
Linux fundamentals: How to copy, move, and rename files and directories
November 20, 2025 - See what it looks like for yourself: $ ls -R dir3 dir4 ./dir3: dir2 file3 ./dir3/dir2: dir1 file2 ./dir3/dir2/dir1: file1 ./dir4: subdir1 ./dir4/subdir1: file4 Β· The cp command copies both files and directories.
🌐
Linux Hint
linuxhint.com β€Ί linux-copy-file-current-directory-rename
Linux Copy File to Current Directory and Rename – Linux Hint
Easy loops allow us to create backup ... file, we copy the files using the syntax of β€œ-orig”. ... The mv command is used to rename the file in the Linux system. For this, we need the current_name and new_name of the directory along with the mv command....
🌐
Stack Overflow
stackoverflow.com β€Ί questions β€Ί 12452101 β€Ί how-to-copy-and-rename-files-in-shell-script
How to copy and rename files in shell script - Stack Overflow
$i"; #Now, we rip off the off just the file name. FNAME=$(basename "$i" .doc) echo "And the basename is $FNAME"; #Now we get the last chunk of the directory ZPATH=$(dirname "$i" | awk -F'/' '{ print $NF}' ) echo "And the last chunk of the path is... $ZPATH" # If we are down a new path, then reset our counter.
🌐
Udemy
blog.udemy.com β€Ί home β€Ί how to rename a file in linux with simple command line options
Rename a File in Linux with Command Lines - Udemy Blog
September 23, 2021 - If we need to rename a single file in Linux, we have two options: we can create a copy of the file with a new name (and delete the old one) or we can rename the file by moving it (with the MV command).
Top answer
1 of 1
2

Having below structure:

β”œβ”€β”€ destdir
└── srcdir
    β”œβ”€β”€ dir1
    β”‚   └── with space.csv
    β”œβ”€β”€ dir2
    β”‚   └── infile.csv
    └── dir3
        └── otherfile.Csv

running the command:

find "/path/to/srcdir" -type f -iname '*.csv' -exec sh -c '
    path="${1%/*}"; filename="${1##*/}";
    echo cp -nv "${1}" "/path/to/destdir/${path##*/}.${filename}" ' sh_cp {} \;

will produce output as following (running in dry mode):

cp -v /path/to/srcdir/dir2/infile.csv     /path/to/destdir/dir2.infile.csv
cp -v /path/to/srcdir/dir1/with space.csv /path/to/destdir/dir1.file with space.csv
cp -v /path/to/srcdir/dir3/otherfile.Csv  /path/to/destdir/dir3.otherfile.Csv

if we remove the echo in front of the cp command (which is used for dry-run) to get copy &rename affective, you will get below structure:

β”œβ”€β”€ destdir
β”‚   β”œβ”€β”€ dir1.with space.csv
β”‚   β”œβ”€β”€ dir2.infile.csv
β”‚   └── dir3.otherfile.Csv
└── srcdir
    β”œβ”€β”€ dir1
    β”‚   └── with space.csv
    β”œβ”€β”€ dir2
    β”‚   └── infile.csv
    └── dir3
        └── otherfile.Csv

note that if there was a same filename and same parent directory name say in sub-directories, it will overwrite with latest file found by the find command, that's why I used -n for the cp command to prevent that, so it will not copy that same file, be noted about that.


Explanation:

find "/path/to/srcdir" -type f -iname '*.csv' -exec sh -c '...' sh_cp {} \;

find files with .csv suffix (ignore-case) recursively and -execute the inline-sh-script for each sh -c '...' we name it sh_cp; the {} is the substitution of the filepath that find command finds it and we pass to our script and that is accessible on $1 or ${1} parameter.

  • ${1%/*}: cuts shortest-suffix from the ${1} parameter (known Shell-Parameter-Expansion), as said above ${1} is the filepath and with this we drop the filename + last / from the filepath and keep only path and store in the path variable.

    ${1}      --> /path/to/srcdir/dir2/infile.csv
    ${1%/*}   --> /path/to/srcdir/dir2
    
  • ${1##*/}: cuts longest-prefix from the ${1} parameter; with this we remove path from the filepath and keep only filename and store in the filename variable.

    ${1}      --> /path/to/srcdir/dir2/infile.csv
    ${1##*/}  --> infile.csv
    

    and accordinlgy:

    path                    --> /path/to/srcdir/dir2
    ${path##*/}             --> dir2
    ${filename}             --> infile.csv
    ${path##*/}.${filename} --> dir2.infile.csv
    

tips:

xYz='to-test/path/to/srcdir/dir2/infile.csv'
${xYz%/*}   --> to-test/path/to/srcdir/dir2
${xYz%%/*}  --> to-test
${xYz#*/}   --> path/to/srcdir/dir2/infile.csv
${xYz#*/}   --> infile.csv
🌐
LabEx
labex.io β€Ί questions β€Ί how-to-copy-file-with-different-name-271252
How to Copy File with Different Name in Linux | LabEx
September 21, 2024 - ## Copying Files with Different Names in Linux In the Linux operating system, you can easily copy a file and give it a different name using the `cp` command.
🌐
nixCraft
cyberciti.biz β€Ί nixcraft β€Ί howto β€Ί bash shell β€Ί linux copy file command [ cp command examples ]
Linux Copy File Command [ cp Command Examples ] - nixCraft
April 6, 2023 - To copy a file to a new file and preserve the modification date, time, and access control list associated with the source file, enter: $ cp -p file.txt /dir1/dir2/ $ cp -p filename /path/to/new/location/myfile This option (-p) forces cp to preserve ...