简体   繁体   中英

Linux : combining the “ls” and “cp” command

The command

ls -l | egrep '^d'

Lists all the Directories in the CWD..

And this command

cp a.txt /folder 

copies a file a.txt to the folder named "folder"

Now what should i do to combine the 2 command so that the file a.txt gets copied to all the folders in the CWD.

The cp command does not take several destinations, but you could always try:

for DEST in `command here` ; do cp a.txt "$DEST" ; done

The command inside the backticks could be a command that produces a list of directories on standard output, but I doubt that ls -l | egrep '^d' ls -l | egrep '^d' is such a command. Anyway, the title of your question being about combining ls and cp commands, this my answer. To actually achieve what you want to do, you would be better off using find .


Something like find . -maxdepth 1 -type d ! -name "." -exec cp a.txt {} \\; find . -maxdepth 1 -type d ! -name "." -exec cp a.txt {} \\; may do what you actually want. The find command is a special case in that is has a -exec option to combine itself with other commands easily. You could also have used (but this other version fails when there are lots of directories):

for DEST in `find . -maxdepth 1 -type d ! -name "."` ; do cp a.txt "$DEST" ; done

Don't use ls in scripts . Use a wildcard instead.

You'll have to loop over the target directories, since cp copies to one destination at a time.

for d in */; do
  if ! [ -h "${d%/}" ]; then
    cp a.txt "$d"
  fi
done

The pattern */ matches all directories in the current directory (unless their name starts with a . ), as well as symbolic links to directories. The test over ${d%/} ( $d without the final / ) excludes symbolic links.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM