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.
Asked
Active
Viewed 4,715 times
4 Answers
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
-
Or replace the `\;` with `+` to process several files in a single invocation of `sed`. – Jonathan Leffler Jan 28 '13 at 15:10
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 ed :
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