-1

I have a directory containing multiple directories. here is an example of the list of directories:

  • dir1_out
  • dir2_out
  • dir3_out
  • dir4_out

Each directory contains multiple files. For example folder1_out contains the following files:

  • file1
  • file2
  • file3

In the same fashion other directories contain several folders. I would like to add the name of each directory to file name in the corresponding directory. I would like to have the following result in first directory(dir1_out):

  dir1.file1
  dir1.file2
  dir1.file3

Since I have around 50 directories I would like to write a loop that takes the name of each directory and add the name to the beginning of all subfiles.

Do you have any idea how can I do that in linux.

say.ff
  • 373
  • 1
  • 7
  • 21
  • What's the maximum number of characters in your directory and file names? Generally, this is doable but if names are long, on some filesystems you could exceed the path limits (255 character max is common). – jhnc Feb 06 '19 at 04:55
  • maximum number of characters in directory and file names is 45 and 20 respectively. – say.ff Feb 06 '19 at 05:25
  • No problem hitting MAXPATHLEN then. – jhnc Feb 06 '19 at 05:27

1 Answers1

2

A simple bash onliner if there aren't too many files is:

for p in */*; do [ -f "$p" ] && mv -i "$p" "${p%/*}/${p/\//.}"; done

This uses parameter expansions to generate new filenames, after checking that we are trying to rename an actual file - See bash manpage descriptions of ${parameter%word} and ${parameter/pattern/string}

If there may be too many files to safely expand them all into a single list:

#!/bin/bash
find . -maxdepth 2 -print |\
while read p; do
    p="${p#./}"
    mv -i "$p" "${p%/*}/${p/\//.}"
done
jhnc
  • 11,310
  • 1
  • 9
  • 26