-2

I try to use cp to copy a file with a partially dynamic name:

cp google71bg2z2850dafxa3.html DESTIONATION

By principle, the google part of the file name is consistent, but the 71bg2z2850dafxa3 (16 characters) part of the file name is dynamic and I don't want to manually change it in any script, if I don't have to, so I thought about using regex.

In man cp I didn't find any data on "regex" or "regular expressions".
Also, I have tried cp x{2} DESTINATION for a file named x12, which failed.

How to match x number of characters of a file name with cp?

That is to ask; how could I match the 16 characters with some regex?

  • @Theophrastus I am familiar with it to some extent and can post a link to my github own "pocket manual" about it but I want to ensure I match only 16 characters afterwards. – JohnDoea Mar 26 at 4:01
  • @Theophrastus I now recall these from a regex course a few years back, I didn't know it is part of the shell glob system; this might be best although I want to match only numbers and English letters without special symbols. – JohnDoea Mar 26 at 4:05
  • 1
    Yes, just time and again I am surprised by the amount of overlapping; I think it will be helpful to wrap these options into an answer which I will gladly accept and upvote. – JohnDoea Mar 26 at 4:10
  • 3
    cp google????????????????.html DESTIONATION [sic] – pizdelect Mar 26 at 5:25
  • 1
    There is also nothing on globs in the cp manual -- it is not cps job, to glob or regex. – ctrl-alt-delor Mar 26 at 6:38
1

This might be a simplification, but if all of the files in which you're interested are in a single directory, and if none of those files have spaces in their names, you could do something like:

#!/bin/bash
destination="/wherever"
for i in *; do
    if echo "${i}" | grep -q -E '^google.{16}\.html$'; then
        cp "${i}" "${destination}"
    fi
done

Here I'm using grep to do the regex matching: File names that begin (^) with google, followed by any 16 characters (.{16}), followed by .html at the end ($) of the name.

Bash also supports the regex matching too, so you could also do this with:

#!/bin/bash
destination="/wherever"
for i in *; do
    if [[ "${i}" =~ ^google.{16}\.html$ ]]; then
        cp "${i}" "${destination}"
    fi
done

The regex here is the same as my previous example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.