user1293997
user1293997

Reputation: 895

parsing and changing the files in all sub directories

I would like to parse all the files *.c in the sub directories and prefix a string to the file name and place file in the same sub-directory.

For example, if there's a file in dir1/subdir1/test.c , I would like to change that file name to xyztest.c and place it in dir1/subdir1/. How to do that?

I would like to do in bash script.

Thanks,

Upvotes: 1

Views: 150

Answers (3)

tripleee
tripleee

Reputation: 189779

find dir -name '*.c' -printf 'mv "%p" "%h/xyz%f"\n' | sh

This will fail if you have file names with double quotes, or varous other shell metacharacters; but if you don't, it's a nice one-liner.

Upvotes: 0

anubhava
anubhava

Reputation: 785846

A find command with while loop should do that:

PREFIX=xyz; 
while read line
do
   path="$(dirname $line)"
   base="$(basename $line)";
   mv "${line}" "$path/${PREFIX}${base}"
done < <(find dir1 -name "*.c")

Upvotes: 0

sud03r
sud03r

Reputation: 19779

What you need is:

  1. Find all c files in a directory (use find command)
  2. Separate the filname and dirname (use basename and dirname)
  3. Move dirname/filename to dirname/prefix_filename

That should do it.

Upvotes: 1

Related Questions