3

I want to add a comment to all files in a directory in Unix. Please suggest a solution if there is any combination of commands I can use.

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
Ganpat
  • 67
  • 1
  • 5

4 Answers4

6

Using find and sed:

$ find . -maxdepth 1 -type f -exec sed -i '1i #comment' {} \;

This will add the line #comment to the top of all the files in the current directory

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
3

Try doing this using a simple shell concatenation :

for i in *; do
    { echo '# this is a comment'; cat "$i"; } > /tmp/_$$file &&
    mv /tmp/_$$file "$i"
done
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
1

For the fun, try doing this using :

echo $'1i\n# comment\n.\nw\nq' | ed -s file.txt 

Here-doc version :

ed -s file.txt <<EOF
1i
# comment
.
w
q
EOF
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
1

If you want to add a comment to all files with an extension (e.g. ".rb"):

find . -maxdepth 1 -type f -name "*.rb" -exec sed -i '1i #comment' {} \;

And recursive:

find . -type f -name "*.rb" -exec sed -i '1i #comment' {} \;
HectorPerez
  • 744
  • 6
  • 11