First, we have to locate those files:
$ find $folder_name -type f -name "*.js" -print
This will locate all of the files with the suffix of *.js
. The type -f
means only look for files (just incase you have a directory name that ends in .js
). I will assume that your JavaScript file names don't contain whitespace, or control characters like <NL>
characters in the name. Otherwise, we'll have to do a bit more work.
We can use that find statement to locate all of those files, then we can munge those files. Once we find those files, we have to figure out how to munge the file to get the comment line on top.
We'll take three step approach:
- First, we'll create a new file with the comment line in it.
- Next we'll concatenate the old file on the end of the new file.
- We'll rename the new file to the old file.
For the first step, we'll use echo to create a new file with the old name. Then, we'll use the cat command to concatenate the old file on the new file. And, finally we'll use mv to rename the newly constructed file to the old name.
find $javascript_dir -type f -name "*.js" -print | while read file_name
do
basename=$(basename $file_name)
echo "/* $basename */" > "$basename.tmp"
cat "$file_name" >> "$basename.tmp"
mv "$basename.tmp" "$file_name"
done
Note that >
redirects the output of the command to the named file, and that >>
appends the output of the command to the named file. mv
stands for move. In Unix, file are actually stored by inode identify. There's a table of contents that matches the inode to the full name of the file (including the directory). Thus, moving a file in Unix is the same as simply renaming it, so the directory name is changed. In Windows batch, there are separate move
and rename
commands. In Unix, they're both mv
.
Addition
We could use sed
to do an in place prepending of the line:
find . -name "*.js" -print | while read file_name
do
basename=$(basename $file_name)
sed -i "" "1i\\
/* $basename */
" "$file_name"
done
sed
is a powerful line editor, and most people use only its substitution command mode. However, sed
scripts can be way more complex and rich (and obscure which is why you rarely see them).