I have several files generated by a script but I neglected to have the script append a file extension.

Each filename contains the substring k120 and no other file in the directory contains that substring.

I would like to append the .dat extension to each of these files, but I'm very new to bash (and shell scripting in general) and I'm not sure where to start; how can I rename files based on a substring they contain? I figured I could use | grep k120 but beyond that I'm not sure.

I could easily do this with a for loop and a regular expression but I'm guessing that's the wrong (long) way to go about it.

  • It's in the file name. I will edit to clarify.
    – Daniel B.
    Aug 12, 2015 at 21:00

1 Answer 1


Assuming none of your files have spaces:

for i in *k120*; do
    mv -- "$i" "$i.dat"
  • Well ... that's not a thing I knew you could do. How/why does the loop variable get interpreted as "stuff in my directory" as opposed to something else? Oh, * is a path expansion right?
    – Daniel B.
    Aug 12, 2015 at 21:03
  • As in "$i" and "$i".dat ?
    – Daniel B.
    Aug 12, 2015 at 21:09
  • 1
    @Daniel B. If you did, for example, ls *k120*, the shell would expand *k120* into a list of files/directories in the current directory before invoking ls to list them. She shell expands wildcards. In this case, the shell expands *k120* in the same way, so *k120* gets expanded into a space-separated list of matching files. Then the for loop iterates over that list. Each time through the look $i takes on the name of one of those files. Aug 13, 2015 at 14:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .