0

In a bash script i want to copy a file but the file name will change over time. The start and end of the file name will however stay the same.

is there a way so i get the file like so:

  cp start~end.jar

where ~ can be anything?

the cp command would be run a a bash script on a ubuntu machine if this makes and difference.

Sagarmichael
  • 1,624
  • 7
  • 24
  • 53

2 Answers2

4

A glob (start*end) will give you all matching files.

Check out the Expansion > Pathname Expansion > Pattern Matching section of the bash manual for more specific control

   *      Matches any string, including the null string.
   ?      Matches any single character.
   [...]  Matches any one of the enclosed characters.  A pair of characters separated by a hyphen denotes a range expression; any character that sorts between those two characters, inclusive, using the current locale's collat-
          ing sequence and character set, is matched.  If the first character following the [ is a !  or a ^ then any character not enclosed is matched.  The sorting order of characters in range expressions  is  determined  by
          the  current locale and the value of the LC_COLLATE shell variable, if set.  A - may be matched by including it as the first or last character in the set.  A ] may be matched by including it as the first character in
          the set.

and if you enable extglob:

  ?(pattern-list)
         Matches zero or one occurrence of the given patterns
  *(pattern-list)
         Matches zero or more occurrences of the given patterns
  +(pattern-list)
         Matches one or more occurrences of the given patterns
  @(pattern-list)
         Matches one of the given patterns
  !(pattern-list)
         Matches anything except one of the given patterns
Kevin
  • 53,822
  • 15
  • 101
  • 132
  • One bit of advice; try to make the pattern as specific as possible, to avoid matching more files than expected. For example, if you knew the middle part was a timestamp in YYYY-MM-DD format, prefer `start-????-??-??-end.jar` to `start*end.jar`. Or even better, `start-@(19|20)[0-9][0-9]-@([1-9]|10|11|12)-@([1-9]|1[1-9]|2[1-9]|3[01]-end.jar`. – chepner Mar 06 '13 at 16:55
2

Use a glob to capture the variable text:

cp start*end.jar