简体   繁体   中英

Add name of each directory to files inside the corresponding directory in linux

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM