date int64 1,220B 1,719B | question_description stringlengths 28 29.9k | accepted_answer stringlengths 12 26.4k | question_title stringlengths 14 159 |
|---|---|---|---|
1,425,693,332,000 |
Scenario:
Source dirs:
/day1/hour1/instance1/files.ext
/day1/hour1/instance2/files.ext
/day1/hour1/instance3/files.ext
/day1/hour2/instance1/files.ext
/day1/hour2/instance2/files.ext
etc..
Target dir (already exist):
/day1/hour1/instance4/files.ext
/day1/hour1/instance5/files.ext
/day1/hour1/instance6/files.ext
/day1... |
With rsync:
rsync --archive --ignore-existing source_dir/ target_dir/
This will copy the source_dir hierarchy inte target_dir, but will not overwrite any files in the target_dir that already exists.
| Copy all files recursively without replacing |
1,425,693,332,000 |
How can I gzip and copy files to another folder keeping its directory structure with one command in Linux?
For example, I have:
/dir1
/dir1/file1.fit
/dir1/file2.fit
/dir1/file3.fit
/dir1/dir2/file1.fit
/dir1/dir2/file2.fit
/dir1/dir2/file3.fit
After I use a command (Lets we say I copy /dir1 to /another_dir), I want ... |
Assuming you're in the root folder where are all directories for compression (in your case /), you can use find along with xargs command, e.g.
find dir1/ -name "*.fit" -print0 | xargs -i% -r0 sh -c 'mkdir -vp "$(dirname "/another_dir/%")" && gzip -vc "%" | tee "/another_dir/%".gz > /dev/null && rm -v "%"'
Note: You ... | How to gzip and copy files keeping its directory structure? |
1,425,693,332,000 |
In a directory, I have about 150 files with a certain extension, for example:
abc.ext
def.ext
ghi.ext
...
Now I want to copy all of these files also to a new filename (without extension):
abc
def
ghi
What is the shortest way to get this done? Is it possible without writing a loop in a bash file?
Edit: Thank you for ... |
It's possible without writing a script ("bash file"), but not without using a loop:
for f in *.ext ; do cp -- "$f" "$(basename "$f" .ext)" ; done
basename can be used to remove the suffix.
| copy files to a new name - shortest way |
1,425,693,332,000 |
Considering folderA containing those files:
foo
bar
baz
and folderB containing those:
foo
baz
foobar
qux
How can I copy foo and baz from folderA to a new folderC?
Note that I'm comparing only their names, not their contents.
|
Use a for loop over the files. Parameter expansion can be used to extract parts of the path:
#! /bin/bash
for file in folderA/* ; do
basename=${file##*/}
if [[ -f folderB/$basename ]] ; then
cp "$file" folderC/"$basename"
fi
done
You can loop over files in folderB, too, and I'd recommend it if fol... | Copy files from a folder if they're in another folder too |
1,425,693,332,000 |
I'm trying to download a large number of files from a remote server. Part of the path is known, but there's a folder name that's randomly generated, so I think I have to use wildcards. The path is something like this:
/home/myuser/files/<random folder name>/*.ext
So was trying this:
rsync -av [email protected]:~/file... |
Instead of letting the remote shell expand a glob that results in a too long list of arguments, use --include and --exclude filters to transfer only the files that you want:
rsync -aim --include='*/' --include='*.ext' --exclude='*' \
[email protected]:files ./
This would give you a directory called files in the c... | Retrieve large number of files from remote server with wildcards |
1,425,693,332,000 |
Why does a file with a permission of 0664/-rw-rw-r-- become 0777/-rwxrwxrwx when copied onto an external hard drive? The external drive is NTFS-formatted - does this matter?
|
It does matter, because the set of attributes and metadata supported for a file vary widely across the various types of filesystems.
Specifically, the file-system permissions (and ownership, for that) you are referring to here originate in the traditional Unix user management framework and are therefore a feature of t... | File permission change when copying to external hard drive |
1,425,693,332,000 |
I am newbie here, please be patient.
I have a directory containing thousands of files. Filename always start with 1 or 2 letter and have 4 character before underscore "_". The number of files for each pattern can be different, the part of file name after underscore changes.
Sample:
Parentdir:
->AA01_*.pdf
->AA01_*.ht... |
Loop across the set of files. Pick off the alphabetic prefix. Create the directory (if necessary) and move the file into it.
#!/bin/sh
for item in *
do
if [ -f "$item" ]
then
prefix="$(echo "$item" | sed 's/[^A-Z].*//')"
echo mkdir -p "$prefix"
echo mv "$item" "$prefix/"
fi
done
Re... | Sorting and copying files |
1,425,693,332,000 |
I have several folders within a parent folder, which all have the structure below, and am struggling to create a specific loop.
parentfolder/folder01/subfolder/map.png
parentfolder/folder02/subfolder/map.png
parentfolder/folder03/subfolder/map.png
parentfolder/folder04/subfolder/map.png
etc...
so each subfolder conta... |
You may try something like the following for loop,
for d in parentfolder/* ; do
cp "$d/subfolder/map.png" "$d.png"
done
You should run it when your current directory is on the same level of the parentfolder.
| cp command based on parent directory |
1,425,693,332,000 |
Summary
I have copied (rsync --archive) a folder from an ext4 filesystem to a zfs file system with compression on. Now, I'm trying to verify that both folders are identical so that I can safely delete the source folder.
When re-running rsync, no additional bytes are transferred. So, rsync is convinced that both folder... |
md5sum and diff
Under the assumption that the observed differences are the results of different meta data and zfs compression, the respective md5sum of the individual files should still be the same.
cd /path/to/ext4 && find . | xargs md5sum | sort > ~/md5sum-index-ext4
cd /path/to/zfs && find . | xargs md5sum | sort ... | Make sure two folders are identical on compressed zfs and ext4 |
1,537,101,239,000 |
In the following makefile
InputLocation:=./Test
OutputLocation:=$(InputLocation)/Output
Input:=$(wildcard $(InputLocation)/*.md)
Output:=$(patsubst $(InputLocation)/%, $(OutputLocation)/%, $(Input:Input=Output))
.PHONY: all
all: $(Output)
$(OutputLocation)/%.md : $(InputLocation)/%.md
cp -rf $< $@;
ActualFil... |
Run make -n to see the commands that would be executed, or run make without options and look at the commands that are executed. Doing this would probably already answer your question, and if not, it would allow us to know what happens.
From the fragment you show, it seems you want to assign shell variables and later u... | Makefile: Copy using make variables --> error; Not so without variables! |
1,537,101,239,000 |
I have a remote machine with a large number of numbered directories, like so:
dir1 dir2 dir3 ... dir40
each of which contain several numbered files:
file1 file2 file3 ... file2530
I want to copy only a selected range of the files in each directory. Since the files' names are identical in each directory, I want to re... |
You could use rsync, which will do only one ssh to the remote, and provide it with either a complete list of files, or a list of glob patterns of files to copy or not copy. For example,
rsync -navR --exclude='*-[4-9]?.out' --exclude='*-3[3-9].out' --exclude='*-???*.out' myremote:'dir*' mylocaldir
This would exclude ... | Selectively copy from a collection of remote directories |
1,537,101,239,000 |
How can I move files from a full partition to one with more room?
Backstory:
Centos7 partitioned the 1TB hard drive on installation. I didn't realize that the partition mysql installs and runs from only has 50G. It reached maximum capacity and now the mysql service will not start so I can't simply drop or truncate tab... |
You should copy the contents of /var/lib/mysql onto a larger partition, remove the old copy from the space-constrained partition, and create a soft-link to the new location at /var/lib/mysql so that the system will find and use the new location instead.
As requested, here are actual commands, but as always please exer... | How can I move files from a full partition to one with more room? |
1,537,101,239,000 |
I am running the command: sudo rsync -Hva --delete --progress --append-verify "/mnt/1/" "/mnt/2/". I went ahead and modified a text file in /mnt/2/. I then ran the command and I got the following output:
sending incremental file list
sent 13,320,053 bytes received 60,989 bytes 198,237.66 bytes/sec
total size is 1,... |
By default rsync ignores file times and sizes.
The manpage says about --append:
If a file needs to be transferred and its size on the receiver is the same or longer than the size on the sender, the file is skipped.
It shares this quality with --append-verify. The extra verification you were hoping to happen only hap... | Rsync's append-verify isn't mirroring directories |
1,537,101,239,000 |
I am trying to write a script, that will copy file or directory with added timestamp to filename/dirname
Something like:
cover.jpg --> cover_18-01-2014_17:37:32.jpg
directory --> directory_18-01-2014_17:37:32
I don't know how to add the timestamp to filename/dirname. Can anybody help?
Timestamp
now="$(date +'%d-%m-%Y... |
I managed to write script on my own afterwhile
#timestamp
now="$(date +'%d-%m-%Y_%T')"
filename=$(basename "$1")
cp -r "$1" "$2"
if [ -f "$1" ]; then
extension="${filename##*.}"
name="${filename%.*}"
mv -f "$2/$filename" "$2/${name}_${now}.$extension"
else
mv -f "$2/$filename" "$2/${filename}_${now}"... | Adding timestamp to file/dir name |
1,537,101,239,000 |
I have multiple files with an example of how they look like shown below.
-rw-r--r-- 1 my_user users 12 Dec 13 09:56 Example_30_001_20130913175000.DAT
-rw-r--r-- 1 my_user users 12 Dec 13 09:57 Example_30_002_20130913180854.DAT
-rw-r--r-- 1 my_user users 12 Dec 13 0... |
Execute this in the folder of your files:
find . -type f -name "Example_30*.DAT" | awk -F\_ '{printf "cp -v %s Ex_Example_%s.DAT\n", $0, $3}' | bash
find . -type f: search only for files
-name "Example_30*.DAT": file beginning with "Example_30" and ending with ".DAT"
| awk -F\_: pipe this to awk and set the delimite... | Copying and renaming files to a single directory by a single shell script |
1,537,101,239,000 |
I want to list the files in a directory, using ls. Typically, the files in that directory have the same name (except for the extension - one has extension .rej, one has .failed) .
If a pair of files with similar names have the same size, move the .failed file to a specific directory, and leave the .rej alone.
How can... |
You don't want to use ls, you want to use shell globbing and string manipulation:
$ for f in *.rej; do
size=$(stat --printf "%s" "${f%.rej}.failed") &&
if [ $(stat --printf "%s" "$f") -eq "$size" ]; then
mv "${f%.rej}.failed" backup/;
fi; done 2>/dev/null
Explanation
The stat --printf "%s" command will ... | How to ignore files if there is an similar file with the same size? |
1,537,101,239,000 |
On my Ubuntu server there are about 150 shell accounts. All usernames begin with the prefix u12.. I have root access and I am trying to copy a directory named "somefiles" to all the home directories. After copying the directory the user and group ownership of the directory should be changed to user's. Username, group... |
Do the copying as the target user. This will automatically make the target files. Make sure that the original files are world-readable (or at least readable by all the target users). Run chmod afterwards if you don't want the copied files to be world-readable.
getent passwd |
awk -F : '$1 ~ /^u12/ {print $1}' |
while ... | Copying a directory to multiple users home dir and changing user/group ownership |
1,537,101,239,000 |
I have a file that's being constantly held open and continuously modified by another process. This process is continuously seeking to different parts of the file and writing new blocks. I'd like to be able to make a copy of that file but as a snapshot of the file at a single instance of time.
What I don't want to happ... |
Can Linux help me out here?
Yes. But not in the way you probably hoped it would.
So, file systems on Linux generally follow the semantics that a change to a file that is read (in whichever way) should be reflected instantly as possible in all readers of that file. Notice how that is at odds with what you want.
What ... | Can I copy a snapshot of a file that's being constantly modified? |
1,537,101,239,000 |
There are lots of similar questions out there, but none seems to address my problem: every time, the culprit is a legitimate permission issue, or an incompatible filesystem, none of which makes any sense here.
I'm transferring a file locally, on an ext4 filesystem, using rsync. A minimal example is:
cd /tmp
touch blah... |
The OP wrote,
apt-get update && apt-get upgrade, which apparently upgraded rsync (to version 3.2.3-8), fixed the problem.
The error was presumably caused by to a change to lchmod and fchmodat in the GNU C library.
| rsync failed to set permissions for a local copy ("Function not implemented") |
1,537,101,239,000 |
I want to duplicate a folder and all the subfolders, but I do not want to duplicate the contents of the files in this directory.
Let's say the folder I want to duplicate is
Folder0
Folder00
File000.x 1GB
File001.x 500MB
Folder01
File010.x 600MB
I want to create a... |
You can use find:
find src/ -type d -exec mkdir -p dest/{} \; \
-o -type f -exec touch dest/{} \;
Find directory (-d) under (src/) and create (mkdir -p) them under dest/ or (-o) find files (-f) and touch them under dest/.
This will result in:
dest/src/<file-structre>
You can user mv creatively to resolve this... | Duplicating a directory skeleton - Only folders and file names, but not file contents |
1,537,101,239,000 |
I would like to only copy files from S3 that are from today out of a certain bucket with 100s of files. I tried the following: $ aws s3 ls s3://cve-etherwan/ --recursive --region=us-west-2 | grep 2018-11-06 | awk '{system("aws s3 sync s3://cve-etherwan/$4 . --region=us-west-2") }' but it doesn't quite work, I also ge... |
That's because in the second aws s3 you use sync. Try cp instead. Also you can merge the "grep" and "awk" together.
$ aws s3 ls s3://cve-etherwan/ --recursive | awk '/^2018-11-06/{system("aws s3 cp s3://cve-etherwan/$4 .") }'
| Only copy files from a particular date from s3 storage |
1,537,101,239,000 |
This is my first post here, thanks for helping out! I have two external hard drives, HD #1 is NTFS and HD #2 is Mac OS Extended (I think this is the same as HFS+). I am copying many files from #1 to #2 (docs, pics, etc). I want to verify that all items copied correctly.
On #1 (NTFS), folder A reports this size: 8,137,... |
You are comparing directory sizes on two different operating systems with two different file systems. There is no reason to expect them to be the same.
Your real question is how to verify that the data on drive 1 is identical to drive 2. The best tool I have found for accomplishing this is called hashdeep. For more th... | Size difference copying from NFTS to HFS+ |
1,537,101,239,000 |
I have a web server and it using by few developers.
Web-site is under website user. Other users are like user1, user2 etc.
I have given sudo access to user1, user2.. to access website.
The issue I'm having now is users fails to copy scripts from website because some scripts not allows to read directly by the users. An... |
You can do (as user1) something like
sudo -u website cat ~website/somefile > ~user1/somefile
Note that ~user1/somefile will be firstly created by user running the shell (user1), and the cat will be executed as website
You can use tar(1) with same trick, for multiple files:
sudo -u website tar cf - ~website/foo ~websi... | How to copy file from one use to another? |
1,537,101,239,000 |
So for example i have one folder called "test". Inside that folder, i created one another folder called "player" and a lot of text file, let's say 50 files.
[root@ip-10-0-7-70 test]# ls
kaka.txt player rooney.txt
Now i want to move all of that text file into "player" folder. What's the best way to do this?
I tried... |
From the test directory, do:
mv -t player *.txt
Assuming all text files end in .txt.
This will mv all .txt files from current directory (test/) to player/ subdirectory.
| Is there any ways to copy all file to one specific sub-folder under the same parent-folder? [duplicate] |
1,537,101,239,000 |
I have 81 files in .fasta format that contain (up to) 53 items. Such as:
/User/MyData/Sample_1.fasta
/User/MyData/Sample_2.fasta
....
/User/MyData/Sample_81.fasta
Each .fasta file contains a name ID and string of characters delimited as:
>AT1G00001
ATCCACTGCTGTGTACCTGATCAGTGCTGACCCAYTGTGACACTGTG
>AT2G00002
AAAAATTTTG... |
I have the following code for you; below it there's an explanation how it works.
First go into the working directory (cd /User/MyData/) to run this program:
awk '
FNR==1 { sample = FILENAME ; sub(/\.fasta/, "", sample }
/^>/ { target = substr($0,2)".fasta" ; next }
{ print ">" sample > target ; print > ... | How to copy lines from multiple files into one new file and keep file name? |
1,537,101,239,000 |
I'm using a script to download files in two steps:
First, I'm downloading a file containing a list of files from a server to my host machine using rsync.
Then, I'm using rsync to download the actual files (quite a lot) given in the list from the server to my host computer.
The problem is that the script is asking ... |
Your theory sounds right to me. Each time through the for loop when you invoke rsync, it's reconnecting to the server and causing you to be re-prompted.
Rather than loop through the file, ~/list using for you could give this list directly to rsync using the --files-from= switch.
Example
$ rsync --partial -z --files-fr... | Repetition of password while rsync-ing files? |
1,537,101,239,000 |
I have a directory ~/dir that contains a bunch of random folders like: ~/dir/av 801 and ~/dir/lm 320. I want to copy the contents of every inner folder (ie: av 801) into a different directory. The contents of that folder can consist of folders or files.
This is what I guessed the bash command would be:
cp ~/dir/*/* ... |
To copy directories, you need to tell cp to copy recursively by passing it the -r flag.
cp -R ~/dir/*/* ~/target/
If ~/target does not exist, you need to create it first.
mkdir ~/target
| Bash command that uses wildcard in place of folder to copy folder contents of multiple files into one directory? |
1,537,101,239,000 |
Suppose I use cp to copy a directory to another place. If the process takes long, and I create a new file under the source directory, will it be copied, or does it depend on something?
|
If you create a new file while cp is operating, it's likely that it won't be picked up. That might depend on the cp implementation: some gather a list of files when they start, others do it by chunks. If it's a recursive copy, all the cp implementations I've seen work directory by directory, so if you add the file to ... | Will files created under source directory after running `cp` be copied? |
1,337,549,815,000 |
I've been trying to copy some remote files to localhost using regex expression, but it reads the regex as if it would be a regular string and does not find any files matching that.
Any ideas why?
file-download
#!/bin/bash
scp "[email protected]:/home/student/download-this/[a-zA-Z0-9]+\.tar\.gz" .
I have also tried c... |
As said in comments, scp is not regex capable. Better use a glob like this:
scp '[email protected]:/home/student/download-this/[a-zA-Z0-9]*.tar.gz' .
# ^ ^
# need this single quotes
You can't use regex, instead, scp can handle glob, check
man bash ... | SCP not working with RegEx |
1,337,549,815,000 |
I'm trying to copy a command (istioctl) in my home directory on Debian so that I can always use it, as it will be added to my PATH variable automatically.
I tried ("link1" is a symbolic link to a hard drive containing the istioctl):
TestUser@ComputerName:~$ cp ~/link1/istio-1.12.2/bin/istioctl ~/cmd
and
TestUser@Comp... |
You mistakenly thought that the cp command would create a directory at the destination and then put the source file in that directory. It doesn't work like that -- to put a source file into a destination directory, that directory has to already exist; otherwise, cp will simply create a destination file of that name.
T... | Can't get contents of directory in home and can't copy file there |
1,337,549,815,000 |
Example
Suppose I have 2 directories a/ and b/. Let's say they contain the following files:
a/
a/foo/1
a/bar/2
a/baz/3
b/
b/foo/1
b/bar/2
such that a/foo/1 and b/foo/1 are identical but a/bar/2 and b/bar/2 are different.
After merging a/ into b/, I want to get:
a/
a/bar/2
b/
b/foo/1
b/bar/2
b/baz/3
Explanation
a/... |
Can't say that I know of a particular command that would do this for you. But you could accomplish this just using hashing.
Naïve example below:
#!/bin/bash
# ...some stuff to get the files...
# Get hashes for all source paths
for srcFile in "${srcFileList[@]}"
do
srcHashList+="$(md5sum "$srcFile")"
done
# Get ha... | How to merge 2 directories without overwriting *different* files with same relative path? |
1,337,549,815,000 |
Apologies if this seems too basic or has been asked before (I didn't find an answer when I searched but this is also my first time using this website) but I'm a complete beginner who is using Unix for lab research work (in biology- I've never taken a computer science course in my life) at university and this is my lit... |
I know it was quick, but a friend of mine who actually works with computers just happened to get back to me not long after I posted here. I thought I would put the answer so anybody who is having the same problem as me in the future could find it too. The code that worked for me looked like this:
scp myname@host:Direc... | How to save/download a .txt file from terminal to personal computer (OSX) |
1,337,549,815,000 |
I am using the following rsync command which includes the "update" option, meaning it will skip files at the receiver which are newer. It works, except that I need it to tell me the files which were skipped because they are newer on the receiver.
rsync -ahHX --delete --itemize-changes --stats --update /path/to/source/... |
I hope there is a better solution, but this is what I came up with:
First, run this check in the opposite direction of my copy operation:
rsync --dry-run -ahvP --itemize-changes --stats /path/to/receiver/ /path/to/source/
That will tell me which files are newer on the receiver (and will therefore be skipped by my rsy... | rsync: notify of any files that were skipped |
1,337,549,815,000 |
Right now I have following command to copy all contents of the current directory to sub-directory, provided if the subdirectory is created in advance:
cp -p !($PWD/bakfiles2) bakfiles2/
But I have to some times visit those folders which I have never visited before, so sub-directory "bakfiles2" may not exist there, ca... |
cp command doesn't have an option to create destination directory if doesn't exist while coping, but you can achieve with scripting.
or simply use rsync command which can create destination directory if doesn't exist only on last level.
rsync -rv --exclude='_bak_*/' /path/in/source/ /path/to/destination
note that ... | Backup all contents of current directory to a subdirectory inside the current directory, which will be created if not exists |
1,337,549,815,000 |
I want to connect from ServerA to ServerB , and check Oracle Database Status and PendingLogs then record results, and use the result on ServerA ,and compare with the result on serverA and generate logs on serverA.
I used ssh -q [email protected] sh -s < /root/script.sh > /root/output.txt
but I still have to enter pass... |
1- is there any way to turn off interactive login?
Yes, use public key authentication or sshpass to enter password.
2- how can I run script file via spawn ssh ?
Yes, use expect script. If you want to run some other script inside (awk), you need to escape the special characters (\$).
| run script remotely and use result locally with ssh auto login |
1,337,549,815,000 |
#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
cd /home/Sud/Minimal\ Packages/All/
if [ -d $line ]
then
cp $line*.rpm /home/Sud/NewFolder/rpms/
else
echo $line>>/home/Sud/NewFolder/notfound.txt
fi
done < "$1"
I am trying to run the above code to
Read a text file li... |
if cp "$line"*.rpm destination/ ; then
echo $line "successful!"
else
echo $line "not found!"
echo "$line">> /home/Sud/notfound.txt
fi
This worked for me.
| Copy files from a directory if name present in a text file |
1,430,920,409,000 |
ftp -n ${FTP_HOST} << STOP
user ${FTP_USERNAME} ${FTP_PASSWORD}
binary
lcd ${FTP_FROM_DIR}
cd ${FTP_TO_DIR}
put ${reportFileName}
STOP
That is my code which is not successfully copying the file to remote host but using it manually it successfully copies the file to remote host.
When ran from a... |
I suspect part of your issue is with the way you're constructed your heredoc. Try it like so:
$ ftp -n ${FTP_HOST} << STOP
user ${FTP_USERNAME} ${FTP_PASSWORD}
binary
lcd ${FTP_FROM_DIR}
cd ${FTP_TO_DIR}
put ${reportFileName}
STOP
If you truly want those spaces/tabs in the command then you'll need to change to th... | FTP "put" not copying file to remote host when ran from shell script but copies the file to remote host when ran manually |
1,430,920,409,000 |
I'm using CentOS 6.5 and Putty.
My problem is that directory file names are shown in dark blue color which is hard to read. I google searched and found this link; basically it's copying the DIR_COLORS file from /etc to the home directory so changes will only affect the user instead of everyone. The real problem is tha... |
Once the file is copied as per the instructions, just do cd to make sure you're in your home directory, then name_of_your_text_editor .dir_colors and edit the file all you want, and save it. Restart your terminal to see the results.
If for some reason you can't find the .dir_colors file, you could always use whatever ... | cp /etc/DIR_COLORS ~/.dir_colors not responding |
1,430,920,409,000 |
I have a question related to the serial terminal. I have a Linux computer and I connect to an ARM mini-computer running debian with screen /dev/ttyUSB0 115200. From there, I can login and type commands.
That means I can virtually transfer any text file, by creating a file on the ARM through the serial terminal, openin... |
Use shar from GNU sharutils to make a text file out of the binary file, then copy and paste that text file as you’ve been doing. The text file will be a shell script which will recover the original binary file when executed. https://en.wikipedia.org/wiki/GNU_Sharutils
| Send a binary file though serial terminal |
1,430,920,409,000 |
I have something a directory like this
Main Directory
SubDirectory
SubsubDirectory1
xx.jpg
xx,jpg
SubsubDirectory2
xx.jpg
xx,jpg
SubDirectory
SubsubDirectory1
xx.jpg
xx,jpg
SubsubDirectory2
xx.jpg
... |
If the files have non-unique names, then
cp "Main Directory"/*/Subsubdirectory1/* destdir
would overwrite some of the files at the destination. This would also fail if there are thousands of matching pathnames.
To get around this, using GNU cp:
for pathname in "Main Directory"/*/Subsubdirectory1/*; do
cp --backu... | copy files from multiple sub-directories to the same destination directory |
1,430,920,409,000 |
I want to copy files that require root to read/write from one system to another.
My current solution is to use sudo on each system and use tee as shown.
ssh host sudo cat /etc/somefile | sudo tee /etc/somefile > /dev/null
This works but tee sends it's input to stdout so I have to send tee's ouput to /dev/null.
I look... |
There's:
sh -c 'exec cat > file'
Or for arbitrary $files, passed either as environment variables:
sudo FILE="$file" sh -c 'exec cat > "$FILE"'
Or as argument:
sudo sh -c 'exec cat > "$1"' sh "$file"
(where sh goes into $0, and the contents of $file in $1 for that inline script).
(see also >> in place of > to open i... | Does Unix have a command to read from stdin and write to a file (like tee without sending output to stdout)? |
1,430,920,409,000 |
I want to copy files in multiple subfolders with variable subfolder names.
Example:
mkdir rootdir
mkdir rootdir/dir1
mkdir rootdir/dir2
mkdir rootdir/dir3
touch rootdir/dir1/foo.txt
touch rootdir/dir2/foo.txt
touch rootdir/dir3/foo.txt
With known subfolder names, I can copy each file individually.
cp rootdir/dir1/foo... |
There are a few options:
find rootdir -type f -name foo.txt -execdir cp {} bar.txt \;
This searches for regular files called foo.txt anywhere in or under rootdir, and when one is found, cp is used to copy it to the name bar.txt in the same directory. The -execdir option is non-standard but commonly implemented and w... | Copy file in multiple (variable) folders |
1,430,920,409,000 |
Is there any way to archive a folder and keep the owners and permissions intact? I'm doing a backup of some files, which I want to move using a usb-stick, which has a FAT filesystem. So the idea was to keep all this information and file setting within an archive.
I know that the -p option for tar keeps the permissions... |
tar's default mode is to preserve ownership and permissions on archive creation; I don't believe there's even an option not to store the data. When you extract an archive, if you're a normal user, the default is to use stored permissions minus the umask and set the owner to whoever's extracting; if you're superuser, t... | How do I archive a folder keeping owners and permissions intact? |
1,430,920,409,000 |
I'm trying to copy a folder (SRC) containing some files and subfolders.
The content and SRC itself have setgid bit enabled (that is the s in place of the x in the group triplet). Furthermore, the group of the whole content is srcgrp while the files have different owners (let's say me, she and they).
Now, I want to cop... |
You must run the copy command as root as otherwise the owner will be reset to you, and the group may be reset.
sudo cp -a /mnt/d/SRC /home/dog/data/SRC
The full rules are considered in order:
If you are root then all owner/group and permissions are kept
If you are a member of the group then the group name and permis... | Keeping owners in a folder copy |
1,430,920,409,000 |
I found some bottleneck on my workflow which is as follows. I do have one master computer which needs to send data to other node machines. This is done in a for loop such as:
for all nodes: rsync <Options> <Master> <Node>
This works quite nice if the amount of nodes is not to large e.g. 4 or 8 (copying time around 2 m... |
You should have a look to programs which use multicast or broadcast dataframes. Then the master won’t be much limited by the network bandwidth since all files will be transmitted once.
mrsync can be interesting here. There is also uftp.
See https://serverfault.com/questions/173358/multicast-file-transfers
| Methodology to copy data from one machine to many others in a fast way |
1,430,920,409,000 |
We need to periodically archive some big files older than 2 days to a NAS while keeping their directory tree structure. Those files are kept for 7 days in the source directory.
At first we used find for this:
find ${SOURCE_DIR} -type f -mtime +2 -exec ksh -c 'mkdir -p $(dirname ${DEST_NAS_DIR}$0) && cp -p $0 ${DEST_NA... |
If rsync is available on your system, you may use its --ignore-existing flag:
find ${SOURCE_DIR} -type f -mtime +2 \
-exec rsync --ignore-existing '{}' ${DEST_NAS_DIR} \;
Possibly the -u flag might be interesting - it would check if the sender has newer versions of existing files, too, and update them if so.
See if... | In AIX, how to avoid overwrite a file with cp? |
1,430,920,409,000 |
How can I copy a folder that contains symlinks and retain the symlinks in the destination folder? I'm doing something like this with PHP/Bash:
system("cp -r production-clone-target production-sites/{$instanceName}");
but the symlinks do not appear in the destination folder.
|
Try adding the --preserve=links switch to your cp command.
From man cp:
--preserve[=ATTR_LIST]
preserve the specified attributes (default: mode,ownership,timestamps),
if possible additional attributes: context, links,xattr, all
Edit: If under OS X; use cp -a.
| Copy folder with symlinks |
1,430,920,409,000 |
I heard that rsync isn't the best one when creating the first backup in terms of performance. Instead it is the best for the later backups. So I wonder what are some better commands for creating the first backup, and what your usages for them are? Thanks!
Reference:
rsync isn't a good option for copying files to an e... |
rsync is great for keeping two directories up to date by comparing them and only moving over what had changed. You could totally use rsync for the first time. It just will obviously have nothing to compare against and just move everything over. So with that though in mind you could just use cp or scp if you're moving ... | Creating the first backup |
1,430,920,409,000 |
I want to copy new files from my NAS to my external hard drive. I did copy the new files manually up to this point. Now I want to use a script to automate this for me. However everything I tried so far with rsync seems to copy all files and not only the new files.
I tried with the following command:
rsync -ar \
... |
The correct command should probably be this:
rsync --archive --progress --info=progress2 \
'/Volumes/NAS/' '/Volumes/G-DRIVE mobile SSD R-Series'
The -a (--archive) flag implies -t (--times) and -r (--recursive) so you don't need to specify those explicitly. Using --size-only is a poor choice when you have size a... | Copy new files from NAS to External Hard Drive with rsync |
1,430,920,409,000 |
I wish to get a file /export/home/remoteuser/stopforce.sh from remotehost7 to localhost /tmp directory.
I fire the below command to establish that the file exists on the remote host:
[localuser@localhost ~]$ ssh remoteuser@remotehost7 ' ls -ltr /export/home/remoteuser/stopforce.sh'
This system is for the use by autho... |
You are using the --copy-links option. This is documented with the text
When symlinks are encountered, the item that they point to (the
referent) is copied, rather than the symlink. [...]
If your symbolic link does not point to a file that exists, then the --copy-links option would make rsync complain that it can't... | rsync not working even when the destination file exists |
1,430,920,409,000 |
I'm a relatively new Linux user and was transferring over to a new computer, so I decided to copy some files (some configs, downloads, and home files) over to a hard drive (from a previous laptop). Instead of using sudo nautilus I used sudo cp -r instead as I thought it would be faster. But when I transfer over these ... |
As you have used sudo cp -r the new files belong to the root user. If you want to copy files while maintaining the original permissions use sudo cp -p -r.
To "fix" your files now, try sudo chown -R yourusername filepath, where yourusername should be the proper owner of the files, instead of root, and filepath is the r... | Used `sudo cp -r` instead of `sudo nautilus`, can't access files without using `sudo`. How do I copy them ignoring privileges? |
1,430,920,409,000 |
I have many files (with a .fna extension). I need to move them, if they contain the character > a certain number of times.
I know which files contain > a certain number of times (9 times in this example) with this command.
grep -c ">" *.fna | grep ":9"
Which gives an output like this
5242_ref.fna:9
9418_ref.fna:9
Bu... |
You could use zsh with its expression-as-a-glob-qualifier to select files that only have nine such symbols:
$ hasnine() { [[ $(tr -dc '>' < "$REPLY" | wc -c) -eq 9 ]]; }
$ mv *.fna(+hasnine) location/
The first line defines a function whose purpose is to create a true/false filter for files that have nine > symbols i... | move files that contain a pattern a certain number of times |
1,430,920,409,000 |
sorry for my English...
I normality copy a file without options,
cp origin destination
but sometime I to show
cp -u origin destination
In man cp give options as an obligation.
My question can please anyone explains the difference between deploy -u and not used it, I muss to use an option when I'll an ordinary copy f... |
cp -u will only update the destination, if it does not exist or the source is newer that the destination.
| cp without options |
1,430,920,409,000 |
I'm writing a bash script and in it I'm doing something like the following:
#!/bin/sh
read -p "Enter target directory: " target_dir
cp some/file.txt $target_dir/exists/for/sure/
When I run this shell script I see and input:
./my_script.sh
Enter target directory: ~/my_dir
But I get the error/output:
cp: directory ~/... |
Problem is, that ~ is taken literally and not expanded when you type it as input for read.
Test it:
$ read target
~
$ ls $target
ls: cannot access '~': No such file or directory
(note, the quotes around ~)
Use this:
eval target=$target # unsafe
or better, but expands just ~:
target="${target/#\~/$HOME}"
or even b... | cp command saying directory does not exist when it does [duplicate] |
1,430,920,409,000 |
I have millions of xml files in a folder. The name of the files follow a specific pattern:
ABC_20190101011030931_6049414.xml
In this I am interested only in the last set of digits before xml 6049414. I have a list of around 8000 such numbers in a text file. The details in the text file is as follows - a number in ... |
Would something like this make the job ?
pushd /home/iris/filesToExtract
for i in $(</home/iris/hdpvr.txt); do find . -mindepth 1 -maxdepth 1 -type f -name "*_$i.xml" -print0 | xargs -r -0 -i mv "{}" /home/iris/xmlfiles; done
find . -mindepth 1 -maxdepth 1 -type f -name "*.xml" -delete
popd
pushd will move you in ... | Copying files based on partial names in a file |
1,430,920,409,000 |
Let's assume that I have these files:
/1/tEst.mp4
/1/Test.mP4
/1/subdirectory/TEST2.mp4
/1/.20181106Test2.mp4
How can I copy all of these files into /2/Videos with a single command line?
All files that end with “mp4” and have “test” inside the name should be included. Case-insensitive, if possible.
I could use the f... |
This seems doable in bash:
set -o nocasematch dotglob globstar
cp /1/**/*test*.mp4 /2/Videos/
| How to copy all files in all directories with specific filename to one destination? |
1,430,920,409,000 |
I was wondering if I have a file that has apparent size of 1 GiB but actual size of 0 B can get copied to, for example, a USB flash stick with 512 kiB free space?
You can create a file as such using:
dd if=/dev/null of=big-file bs=1 seek=1GiB
Now you can see the apparent and actual sizes:
du --apparent-size -hs big-f... |
Actual size.
Of the destination file.
The simplest implementation is to not try to predict this in advance.
In addition to that, a small fraction is required as overhead. This overhead would be even more complex to predict.
Support for sparse files varies, depending on both the filesystem, and the program making the ... | On copying, which is considered: actual or apparent size? |
1,430,920,409,000 |
I have been facing this issue ever since I started using Linux distributions. While copying/moving either graphically or with cp, one/many big content (anything like a big text file, tar.gz archive, ISO image file, and movies), some part of the content is written to disk and some part cached in memory (RAM). During th... |
As I commented (and for obvious performance reasons) the kernel is using a page cache. So this is a feature, not a problem. See http://linuxatemyram.com/ for more.
You could (but I don't recommend doing that) using some mount options (to disable, or lower the use of, the page cache), and you need to umount any device ... | Content cached in RAM while writing to disk - Linux |
1,430,920,409,000 |
i am trying execute ssh-copy-id in one port different than 22 (default). I researched and found the command below
$ssh-copy-id -i ~/.ssh/id_rsa.pub "[email protected] -p 22001"
but, when execute the command, i got this error:
/usr/bin/ssh-copy-id: ERROR: ssh: connect to host 192.168.0.1 -p 22001 port 22: Connection re... |
$ ssh-copy-id
Usage: /usr/bin/ssh-copy-id [-h|-?|-n] [-i [identity_file]] [-p port] [[-o <ssh -o options>] ...] [user@]hostname
So in your case simply use:
$ ssh-copy-id -i ~/.ssh/id_rsa.pub -p 22001 [email protected]
Because of your usage of quotes, the -p 22001 part became part of the hostname which explains the e... | ssh-copy-id different port |
1,430,920,409,000 |
What I want to do is basically
cp long/directory/path/file long/directory/path/file-copy
This or similar operations are pretty common. Typing out the whole path twice is obviously awkward, even with auto-completion or copy-paste. There are a couple of simple ways to do it, but none seems ideal:
First cd into the di... |
As per this question, you can use:
cp /long/path/to/file{,-copy}
This a shell expansion done by bash (not sure about others), so it will work with any command.
| How to copy a file within its original directory, most easily? [duplicate] |
1,430,920,409,000 |
I guess the question first has to learn from your comments, before it grows into a grown-up question.
Here is the tricky situation:
I have a folder destination with many files (pdfs), that, unfortunately, have the same, recent, timestamp (date of last change of file). However, these timestamps are wrong, they merely r... |
It seems to me that you don't really want to copy the files at all, but just fix up the metadata (date).
Accordingly you can use something like this:
rsync --dry-run -av --existing --size-only src/ dst
The directories src and dst are the source and intended destination directories. When you're happy it looks like it'... | fixing metadata if destination file is younger than source file |
1,430,920,409,000 |
Example I have these files
/sdcard/testfolder/file1
/sdcard/testfolder/file2
/sdcard/testfolder/file3
/sdcard/testfolder/file4.ext
I would like to create .sha256 files for each
/sdcard/testfolder/file1.sha256
/sdcard/testfolder/file2.sha256
/sdcard/testfolder/file3.sha256
/sdcard/testfolder/file4.ext.sha256
The meth... |
What I would do:
find /sdcard/testfolder -not -name '*sha256' -type file -exec sh -c '
sha256sum "$1" > "$1.sha256"
' sh {} \;
| How to recursively create .sha256 hash files for every file in a folder? |
1,430,920,409,000 |
I need to find all project.updated files in some nested directory and use these files for content replacement of project.json file in the same directory.
I'm using BusyBox (1.33.1).
/apps
/project1
project.json
project.updated
/project2
project.json
As you can see, there is a project.u... |
Use find and -execdir which executes the given command in the directory where the file is found:
find /apps -type f -name '*updated'\
-execdir bash -c 'cat "$0" > "$(basename "$0" .updated).json"' {} \;
For a dry-run, just echo the command first and maybe print the found file:
find /apps -type f -name '*updated' -pri... | How to replace content of nested files? |
1,628,689,358,000 |
I have a directory structure like this;
dir
├── dirA
│ └── file1
│ └── subdir
└── dirB
└── file2
└── subdir
I need to move file1 to dirA/subdir and file2 to dirB/subdir. How can I do it in Linux?
|
Gnu find
find dir -mindepth 2 -maxdepth 2 -type f -execdir sh -c 'mv -t ./*/ "$1"' find-sh {} \;
find dir \
-mindepth 2 -maxdepth 2 -type f \
-execdir sh -c '
mv -t ./*/ "$1"
' find-sh {} \;
original directory structure
dir
├── dirA/
│ ├── fileA
│ └── subdir/
│ ├── e
│ ├── q
│ └─... | Move multiple files to subdirectories in linux |
1,628,689,358,000 |
I have a directory which has many sub-folders and under sub-folders there are other sub-folders. I want to copy all the directory and subdirectories into another location with copying only files with certain names in these directories (while preserving the hierarchy).
Let's say, copy all the directory and sub-director... |
Using rsync:
rsync -a --include='*/' --include='*.txt' --exclude='*' source_dir/ target_dir
This should create a copy of the source_dir directory hierarchy as target_dir, with files whose names match *.txt copied (only).
The --include and --exclude options are handled in a left-to-right fashion and the first pattern ... | Create the same subfolders in another folder with copying files with certain names |
1,628,689,358,000 |
I'd like to move a folder that contains multiple files within it from my local folder to a ssh [email protected] machine's temp drive. What would be the best method in doing this? Thanks for your help.
|
You will need to be able to ssh as a user who has write permissions to that system's /tmp directory or wherever you are trying to copy the filed. Assuming that you can:
rsync -avhH /directory/to/copy user@system:/tmp
scp -r /directory/to/copy user@system:/tmp
If the user can't write to the directory, assuming it's /... | Moving a file from local drive to a remote machine |
1,628,689,358,000 |
I have a folder(A) which is structured like this
Main Directory(A)
|
|
Subdir------Subdir2-----Subdir3
| | |
| | |
f0--f1 f0--f1 f0--f1
I want to copy and paste all files(recursively) in A to a new directory B. BUT I don'... |
Simple, in a shell :
$ find A -type f -exec cp {} B \;
| Copy files from folders and sub folders without preserving directory structure |
1,628,689,358,000 |
I am trying to copy/move a large file (15 GB) to a directory in Linux and want to have a dependency on that event.
Now lets say I have a file named abc.txt, and I am running below command:
mv /usr/tmp/abc.txt /usr/data/
When the move process start I see a file in data directory with the actual file name i.e. abc.txt... |
You must be moving between two different filesystems, so in effect the file is copied. Try to first copy it then, and after that's done, move within the destination. This should do:
mv /usr/tmp/abc.txt /usr/data/.abc.txt && mv /usr/data/.abc.txt /usr/data/abc.txt
I assume your watching process won't recognise the hid... | Copy or move large file with transient name till the file is completely transfered to destination in linux |
1,628,689,358,000 |
I've been trying to find a way to free up some space on a drive by moving folders to another. I have a folder full of stuff I can move, doesn't need to be all of it, to free up some space.
In Windows I'd just select a bunch of folders, get the properties, it'd tell me how much space it was taking up, I'd select more o... |
On a GNU system, you could script it as:
#! /bin/bash -
usage() {
printf >&2 '%s\n' "Usage: $0 <destination> <size> [<file1> [<file2>...]]"
exit 1
}
(($# >= 2)) || usage
dest=$1
size=$(numfmt --from=iec <<< "$2") || usage
shift 2
(($# == 0)) && exit
selected=()
sum=0
shopt -s lastpipe
LC_ALL=C du -s --null --bloc... | How to find the first X gb of data? |
1,628,689,358,000 |
What is the most accurate way to copy a file or a folder from one linux machine to another using commands?
|
There are various options like ftp, rsync etc. but the most useful of these is the scp which comes preinstalled with openssh package. Syntax is simple:
scp file.txt user@host:/folder/to/which/user/has/permissions
There are some other flags, for example, if you are using a different port other than 22 for ssh, you'd n... | Methods to copy a file or a folder one linux server to another linux server [closed] |
1,628,689,358,000 |
A fried of mine gave me her laptop because it was behaving wierdly. This was (Still is) a hard drive failure, and I suggested her to backup her files before installing a new hard drive.
I booted the computer with Ubuntu on a flash drive to backup her files (Mainly family picture and movies), but I still struggle to co... |
If you have a spare disk of equal or greater size you could use ddrescue to clone the drive which will attempt to recover good parts during a read error.
WARNING: these are destructive commands, if you get them wrong you could lose data - double check you have the correct drives before you run them.
Assuming /dev/sdf ... | Copy files from a failing drive |
1,628,689,358,000 |
I have a directory with many files in it. The only ones I care about are those with the extension .jar. However, there are other files in the directory as well.
I have a source directory with only .jar files. I want to achieve the equivalent of:
rm destdir/*.jar
cp sourcedir/*.jar destdir
However, I want to do thi... |
You can use:
rsync -av --include='*.jar' --exclude='*' --delete \
sourcedir/ destdir/
The -a option is archive mode, it preserves things like links and timestamps (check the man page for a full explanation). The -v is for verbosity, remove if you don't care about logs.
That should handle your first three option. ... | How to use rsync to force all *.jar files to match? |
1,628,689,358,000 |
I 'm working on a bash script to copy files from a single USB drive to multiple others.
I'm currently using rsync that copies from the source to a single destination, going through all of the output drives in a loop one at a time:
for line in $(cat output_drives_list); do
rsync -ah --progress --delete moun... |
I can not test it but if you start more processes in the background it might be the solution:
START=$(date +%s)
for line in $(cat output_drives_list); do
rsync -ah --progress --delete mountpoints/SOURCE/ mountpoints/$line/ &
done
jobs # get a list of running jobs
wait # wait for all processes to complete
sync
echo... | Fastest way to duplicate files from one USB flash drive to multiple others? |
1,628,689,358,000 |
I have a long list of folder as follow:
001_bat_3513
002_mon_3213
003_bat_3515
004_btt_3540
005_bat_4513
055_bpt_8523
056_bot_3513
058_bat_1513
.
.
From this list:
How can I copy the folders ( and all its content) that has the part " bat" in its name?
|
You can use shell globbing for this:
cp -rp *bat*/ /destination/
Here *bat*/ will expand to directories having bat in their names.
Or using find, which will work even if there are so many files that you get an error because the command line is too long:
find . -maxdepth 1 -type d -name '*bat*' -exec cp -rpt /destinat... | Copy folders has specific part of name and it is content |
1,628,689,358,000 |
I had an external hard drive that I mounted internally. It came formatted with NTFS, and I wanted to move to ext4. So I copied everything I wanted to keep onto other drives, created a brand new partition table (GPT) with a single ext4 partition, and now I'm trying to copy everything back. I'm using rsync -a --info=... |
This looks like a hardware issue, rather than a kernel bug. You can try the following:
re-seat the SATA cable
use another SATA cable
run SMART diagnostics (the self-tests, see smartmontools)
run a destructive badblocks scan
If you have a spare drive or computer you could also try switching (use another drive in the ... | Filesystem errors when restoring many files |
1,628,689,358,000 |
I want to copy the last used (or maybe created) files of a total size to another folder. Is this possible without additional tools?
I have an USB drive of a certain size that is less than the total size of a folder. As I can't copy all files to USB I like to copy based on latest usage until there is no more space. Ide... |
On the assumption (based on the [linux] tag) that you have bash available, as well as the stat and sort commands; on the further assumption that you want to sync the most-recently-modified files first (see man stat for other timestamp options), then here is a bash script that will loop through all the files in the cur... | Copy last used files of total size |
1,628,689,358,000 |
I have like 5GB of data and a very slow USB-Drive.
Should I use dd, cp or rsync?
Should I compress them first into for example 7z / tar or not?
In short: What is the best way and the best practices to copy all those files to the USB-Drive?
Thanks for your help :)
|
One good way is to compress them (on the same media where they are) and the transfer the archive to USB drive. Using this way you will have much less updates on USB for filesystem and less operations create/open/close (related to files).
About copy operation for me cp will be OK.
| How to Tranfser huge amount of Files to slow USB Drive (dd, cp, rsync, 7z, tar) |
1,628,689,358,000 |
I have computer 1 logging voltage data to a file volts.json every second.
My second computer connects via ssh and grabs that file every 5 minutes. Splunk indexes that file for a dashboard.
Is scp efficient in this manner, if so then ok. Next is how to manage the file and keep it small without growing to 2mb lets say? ... |
To keep directories synchronized through ssh,the typical tool is rsync.
To roll log files and save space, logrotate is well dedicated.
To secure an unattended simple task through ssh, .ssh/authorized_keys with forced command is an excellent practice.
Example:
set /etc/logrotate.d/volts file (imitate classical sysl... | How can I optimize the transfer of files between two systems and also trim the file |
1,628,689,358,000 |
I want a script to copy the same file from source folder to target folder by incrementing the filename (ex. file1, file2, file3, file4,....). This would be for some performance testing.
I've got this code so far, but how best can it be achieved?
#!/bin/sh
for i in 1 2
do cp /tmp/ABC*/folder1/ABC*$i
done
|
You want a forever-repeating loop
#!/bin/sh
n=1
while true
do
cp /tmp/ABCfile "/mnt/share/reception/13_calling_cards_data/ABCfile.$n"
n=$(( n+1 ))
done
| script to copy same file to a folder continuously in linux |
1,628,689,358,000 |
I'm a first time poster & new-ish to coding:
I need to copy a file ING_30.tif into 100s of folders, so I'm hoping to use a terminal command to do this quickly.
Both ING_30.tif and the folders I need to copy it into are in the same parent folder, ING/.
I don't want to copy ING_30.tif into every folder in ING/, just th... |
Another option:
for d in AST*/; do cp ING_30.tif "$d"; done
This will loop over all directories (enforced by the trailing /) that match the glob pattern AST* and copy the file there.
This is safer than using xargs in case your directory names can contain spaces or other funny characters (see answers to this question ... | Copy file into multiple folders, but only when starting with AST |
1,628,689,358,000 |
This is something I imagine I might have to submit a patch or feature request for, but I'd like to know if it is possible to create a hardlink to a file, that when that hardlink which was not the original file is editted, that it would be copied first before it was actually editted?
Which major filesystem would this a... |
After you create a hard link to a file, there are just two links to one file. While you may remember which link was first and which was second, the filesystem doesn't.
So it is just possible for an editor to determine whether there is more than one link to a file or not. An editor may or may not preserve the link when... | How can I have it so, that when hardlinks which are not the original, are editted, that they would first be copied then editted? |
1,628,689,358,000 |
I am trying to back up data (230 GB, 160k files), over USB3.0 to a newly bought external Seagate Expansion Portable Drive of 4 TB, formatted as NTFS. I am running Ubuntu 18.04.3 LTS.
I first tried using a simple cp command in the terminal, but after only copying a few percent, the copying started stuttering and became... |
Thank you for all your help.
I have now solved the issue. I reformatted the drive to ext4 and after that I used the command
rsync -avhW source dest --inplace --exclude=".*/"
where
-a is for archive, which preserves ownership, permissions etc.
-v is for verbose, to see what is happening
-h is for human-readable, so th... | copying files (cp and rsync) to external HDD causes i/o errors and loss of data on destination |
1,628,689,358,000 |
Like many teams, we now have people working from home. These remote clients are behind firewalls (which we do not control), and they do not have static IP addresses. In short, we cannot directly SSH into these clients. However, the clients can SSH into our server. (Hardened SSH is already set up on all clients and the... |
A number of thoughts
Your script is (presumably) running as root, so that netstat -Wpet can run and sudo -u ${user} operation is simplified.
Using a reverse connection such as ssh -R 20202:localhost:22 centralserver I cannot get a port and user combination from the netstat | grep | grep | cut ... line.
netstat -Wpe... | efficiently rsync multiple clients (which are behind firewalls) to a server |
1,628,689,358,000 |
I have Ubuntu installed on a VM on my PC.
I need to copy some folder ( recursively ) from Ubuntu to the server.
If I want to download the folders from the server to my VM machine I did this:
rsync -av [email protected]:/home/my_folder ./
my_folder contains other folders and files.
What if I want to upload a folder to... |
You'd just need to switch the arguments (which represent source and destination) like
rsync -av ./newfolder [email protected]:/home/my_folder
Have a look at man rsync which explains that a trailing slash after newfolder would only transfer the contents of said directory - in this case, you might want to change the up... | Push folders with rsync on a server |
1,628,689,358,000 |
I am using Manjaro Gnu/Linux and I have a directory named files. Under this directory, I have around 650 sub directories, with names such as: dir1, dir2, dir3, dir4, ...
Under each sub directory there are varying number of .jpg images (say, from 2 to 11).
Say as an example, under dir1 subdirectory, the images are imga... |
You could run this script in the directory named files:
mkdir all_images
find -type f -name '*.jpg' -exec sh -c '
c=1
for f in "$@"; do
pdir=${f%/*}
pdir=${pdir##*/} #Now pdir conains the parent directory name
cp -- "$f" "all_images/${pdir}_${c}.jpg"
c=$((c+1))
done
' findsh... | Copying and renaming images |
1,628,689,358,000 |
I have a case when I need to move data from an old server: host1 to a new server: host2.
The problem is host1 cannot see host2, but I can use another server (localhost) to SSH to both host1 and host2.
Imagine it should work like this: host1 -> localhost -> host2
How can I use rsync to copy files between host1 and hos... |
I ended up with the solution from https://unix.stackexchange.com/users/312074/eblock
with
scp -3 host1 host2
| How to use rsync to copy files between 2 remote servers based on the localhost server? [duplicate] |
1,628,689,358,000 |
I have the following directory structure:
top_dir
|________AA
|_______f1.json
|_______f2.json
|________BB
|_______f1.json
|_______f2.json
|________CC
|_______f1.json
|_______f2.json
I would like to write a script / command line com... |
Using a loop:
mkdir /path_to/new_dir
cd /path_to/top_dir
for i in */*.json; do
cp "$i" "/path_to/new_dir/$(basename "$i" .json)_$(dirname "$i").json"
done
$(basename "$i" .json) prints the filename without suffix, e.g. f1
$(dirname "$i") prints the directory name, e.g. AA
| Copy files with the same name but in different dirs into a new dir while renaming them |
1,628,689,358,000 |
I regularly update my system running KDE Neon, but this time after the update something broke in the "file copy" process. The system slows down during copying to external hdd or pendrive so much so that the system becomes unusable, CPU usage runs too high. Initially after reading some online forums I thought it was so... |
After a bit of research I noticed the kernel was updated to 5.3 from 5.0, it was certainly due to system updates. After downgrading the kernel to 5.0 all things came back to normal. I dont know whats wrong with version 5.3, but it resulted in very high cpu usage specially mount.ntfs process which is around 60 to 70 pe... | Copying files slows down the system, making it unusable (KDE Neon) |
1,558,719,020,000 |
I have a deeply nested folder structure in which there are hundreds of files called data.log. I need a script to rename each of these data.log files according to the name of the parent folder they are in and then move the renamed filed to a defined target folder. The original data.log files should remain in place.
Exa... |
#!/bin/bash
OUTDIR=/opt/slm/output/
find /opt/slm/data -name data.log |
while read FILE; do
OUTFILE="$(basename "$(dirname "$FILE")")"
cp -p "$FILE" "$OUTDIR$OUTFILE"
done
| Special "copy and rename" case |
1,558,719,020,000 |
Is there an elegant and fast way to copy a certain directory structure and only select a random amount of files to be copied with it. So for example you have the structure:
--MainDir
--SubDir1
--SubSubDir1
--file1
--file2
--...
--fileN
--...
--SubSubDirN
--file1
--file... |
Since you tagged this as linux I'll assume GNU utilities.
Copy directory structure from $src to $dest:
find "$src" -type d -print0 | cpio -padmv0 "$dest"
Also copy a random sample of $nfile files from each leaf subdirectory of $src:
find "$src" -type d -links 2 -exec \
sh -c 'find "$1" -type f -print0 | shuf -z -... | Copy directory structure with random number of files |
1,558,719,020,000 |
I want to move files from directory A to directory B. But there are some conditions.
directory A structure:
a.txt_20170502
b.txt_20170502
a.txt_20170507
asd.txt_20170509
asd.txt_20170522
So, I want to rename a.txt_20170502 to a.txt and move that file to directory B, but if a.txt is present in directory B, it will ... |
for file in A/*.txt_*; do
newfile="B/${file##*/}" # remove A path, add B path
newfile="${newfile%_*}" # remove trailing suffix
if [[ ! -f "$newfile" ]]; then
mv "$file" "$newfile"
fi
done
This will iterate over all files in A that matches *.txt_*. It will construct a new file path by replacing the A pa... | move only uniq files from one directory to other [closed] |
1,558,719,020,000 |
Very simple script to copy a file
#!/bin/bash
#copy file
mtp-getfile "6" test2.jpg
I set it as executable and run it using
sudo sh ./test.sh
It gives me a file called test2.jpg that has no icon and I cannot open
I get a 'Failed to open input stream for file' error
However, if I simply issue the following from the c... |
Need to do
sudo chown <user> <copied file name>
Not sure why permissions would be different in each case
| copying binary file(.jpg) works from command line but not from script |
1,558,719,020,000 |
We are using the following rsync command in a script to copy files from source to destination.
rsync -av --exclude 'share/web/sessions/' --rsync-path "sudo rsync" /sdata/ 172.31.X.X:/sdata/ &>/home/fsync/rsyncjob/output
Now, we have a cleanup script on source host which is removing some of the files after some parti... |
I would not use --delete-after because it forces rsync to rescan the file list.
Best option today is to use --delete-during (or --del for short). If you want to retain the "delete after" effect due to I/O error concerns, use --delete-delay.
See the man page for reference:
Some options require rsync to know the full f... | Using --delete option with rsync |
1,558,719,020,000 |
I want to do this. I want to create an alias called 'bu' (backup). The bu alias would call upon the copy tool to copy any file passed to a directory I will manually setup in /root/backup/
$bu testfile.txt
cp testfile.txt /root/backup/
So I think I need to create a bash script, and point the alias to that script ( c... |
You can use a bash script called bu. Put this code inside a file bu:
#!/bin/bash
cp "$1" /root/backup
and then save it in your $PATH or add the directory where you put the file to your $PATH. Lastly make the script executable: chmod +x bu.
| attempting to create a script, with an alias, that will backup a single file |
1,558,719,020,000 |
We are using rsync to copy files from one location to another location on a different host. We want to exclude a directory from the source location so that files from this directory are not copied . The files inside this directory are actually session data and this data were removed once the session completes . So we... |
Always try to see if there's already a similar discussion before posting the question.
With rsync, all exclude (or include) paths beginning with / are are anchored to the root of transfer. The root of transfer in this case is /share. Use relative path, instead of absolute path and it should work.
For further reference... | rsync failing to exclude directory [duplicate] |
1,558,719,020,000 |
I have OpenBSD 5.6 installed on my notebook computer and would like to copy files from my USB flash drive to the root of the installed OS. I figured out how to mount the USB drive using these commands:
# mkdir /mnt/usb
# mount /dev/sd1i /mnt/usb
# cd /mnt/usb
How do I copy files from /mnt/usb to the root of the insta... |
The basic command to copy files is cp. You might want to use ls first to get a list of files (and directories):
cp some_file ~/new_name
copies a file under /mnt/usb to the file new_name in your home directory.
If you want to copy all files ending in .jpg and .JPEG to a new directory pictures under your home directory... | Copy files from USB flash drive to root in OpenBSD |
1,558,719,020,000 |
I did this to copy files between Windows and Linux.
C:\Documents and Settings\668340\My Documents\putty>pscp "C:\Documents and Settings\563456\abc.txt" "[email protected]:/home/auto/"
But it prompts for a password and how do i automate this task using private/public key pairs between windows and linux
Even winscp wo... |
As you want to authenticate without prior key exchange, I see no other option than using password authentication (at least the first time).
So you need to hard-code the password in your script. You can give the password to pscp with its -pw option. But, I do not know how safe this is (at least in Linux, all user norm... | how to copy files from windows to linux witout password using a script or program? |
1,558,719,020,000 |
I have an issue where I want to connect a very old system (UNIX) to a new machine. This old machine logs in by scp using a hardcoded oldsystemaccess user and copies a file into a subdirectory of the new servers webroot /var/www/newserver/test/import. The new machine is running an Ubuntu 18 LAMP stack with no advanced ... |
On some systems (like FreeBSD if you believe Wikipedia), the setuid bit on a directory would have my desired behaviour (Link). But since it is not default behaviour on the Ubuntu I am running I found the solution for the problem I am having was the following:
Set the setgid bit using chmod so new files are owned by th... | Change owning user and group on file creation |
1,558,719,020,000 |
I have two directories, lets call them X and Y
Within them I have 100k+ files, .jpg files in X and .txt files in Y
I want to randomly select N files from X and copy to folder Z
This should be manageable using find + shuffle.
I then want to find all of the files in Y with the same names of the files that were copied to... |
#!/bin/bash
X=/path/to/X
Y=/path/to/Y
Z=/path/to/Z
mapfile -d '' -t files < <(find "$X" -type f -name '*.jpg' -print0 |
shuf -z -n 10 -)
for f in "${files[@]}"; do
echo cp "$f" "$Z"
bn=$(basename "$f" ".jpg")
echo cp "$Y/$bn.txt" "$Z"
done
This script is untested but should do a dr... | Selecting n random files from one directory and copying them to another folder + other files with same same, but different filetype |
1,624,962,712,000 |
I need to copy some files that are like this:
folder1/name1.csv
folder1/name2.csv
folder2/name1.csv
folder2/name2.csv
folder3/name1.csv
folder3/name2.csv
All folder* are subdirectory of a directory.
What I want to do is to copy all the file "name*" into a new directory new_dir but I have to change their name.
Looking... |
Given
$ tree folder*
folder1
├── name1.csv
├── name2.csv
└── name3.csv
folder2
├── name1.csv
├── name2.csv
└── name3.csv
folder3
├── name1.csv
├── name2.csv
└── name3.csv
0 directories, 9 files
then using a shell loop with parameter expansion to slice'n'dice the names
$ for f in folder*/name*.csv; do
b="${f##*/... | Copy and rename files adding a dynamic prefix/suffix |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.