-1

I want to copy and paste file in linux, but i want to keep only the two last increment of filename, for example my code generate a list of file :

aa001 bb001
aa002 bb002
aa003 bb003
aa004 bb004

So I want to keep the two last increment ( *003 *004), and copy in other directory.

daday001
  • 91
  • 1
  • 9

3 Answers3

0

Assuming that your list of files is in the file filelist

cat filelist | tail -n 2 | tr '\r\n' ' ' | xargs -d " " -L1 -I{} cp {} "tdir/"

Note that if your code is generating a list you can pipe that straight in instead of writing it to filelist first.

Tail will only pass on the last 2 lines of the file which contains the files you want to copy. Changing the -n 2 to -n 1 or -n 3 will change the number of files that will be copied.

Tr will convert any newlines to spaces, this allows xargs to split the new list nicely.

Xargs will call cp with each space separated value piped into it, placing them into tdir

You can add the --verbose switch to xargs to see the calls it is making to cp.

Check out man pages for tail, tr and xargs for more details.

Michael Shaw
  • 294
  • 1
  • 11
0

Assuming your target folder is b, you can use find like this:

find -maxdepth 1 \
     -type f \
     -exec \
    bash -c 'f="$(basename "{}")";cp -v "$f" "b/${f##[a-z]*[a-z]}"'

Probably it would be better and more readable to create a separate shell script which does the copy work and call it from find:

copy.sh:

#!/bin/bash

source_file="$1"
source_basename="${source_file##*/}"

dest_folder="$2"

dest_file=${source_basename##[a-z]*[a-z]}
dest_file="$dest_folder/$dest_file"

cp -v "$source_file" "$dest_file"

Then call it like this:

chmod +x copy.sh
source_path="/path/to/source"
dest_path="/path/to/dest"

find "$source_path" -maxdepth 1 -type f -exec ./copy.sh {} "$dest_folder" \;
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
-1

Thanks you for your answer i have find another way (inspired to the first reply) so I make that :

ls -1t aa* | head -2 |  tr '\r\n' ' ' | xargs -d " " -L1 -I{} cp {} "tdir/"

Simple way with the ls -1t aa* | head -2 , I recover the two last file modified and start with aa*, and next i copy in tdir directory.

daday001
  • 91
  • 1
  • 9