Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How do I add a new line at the beginning of every file in /home/johnny containing the text "Hello", followed by a blank line? Also, I have to delete every useless space or tab at the ending of every line(if a line contains only spaces or tabs, they will be deleted, but the line must be kept).

share|improve this question

Try the following (started in /home/johnny/):

for f in * ; do awk 'BEGIN {print "Hello\n";} {gsub("([ \t]+)$", ""); print $0; }' "$f" >"$f.2"; done

It creates .2 files in the same directory. These files contain the modifications.

The for statement lists all files in the directory. If you'd like to process only text files, you could use *.txt instead of *.

The awk performs 2 tasks:

  1. Prepends each file with "Hello" and the blank line.
  2. Removes spaces and tab characters from the end of each line.

The results are displayed on the standard output.

Finally a simple redirection creates the .2 files from the processed standard output.

It works on files with spaces in their names, because $f is quoted.

If you do not want to keep the original files, modify the command as follows:

for f in * ; do awk 'BEGIN {print "Hello\n";} {gsub("([ \t]+)$", ""); print $0; }' "$f" >"$f.2"; mv "$f.2" "$f"; done

The main addition is a move command that replaces the original files with the modified version.

share|improve this answer
do I have to make a script containing those instructions or the instructions can be put directly in the terminal? And if I do not want to keep the original files What do I do? – johnny Nov 12 '11 at 21:14
You can put the command into a single line. (This is how I tested it.) I've updated the answer with the option to replace original files. – lgarzo Nov 12 '11 at 21:49

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.