0

I have a file with this content:

dog 
cat

and I want to add a sentence (I have a) before every sentence, so the new content should be:

I have a dog
I have a cat

I tried with

sed -i 'I have a ' file

But I get something like this

I have a 
dog
I have a
cat

Which would be the correct use of sed? Is there another way of doing?

Iker Aguayo
  • 3,980
  • 4
  • 37
  • 49

3 Answers3

4

You can use sed:

sed -i.bak 's/^/I have a /' file
cat file
I have a dog
I have a cat

Or awk:

awk '{print "I have a", $0}' file
I have a dog
I have a cat
anubhava
  • 761,203
  • 64
  • 569
  • 643
4

With bash:

while read -r line
do
    echo "I have a $line"
done < file > tmp_file && mv tmp_file file

Basically, read each line and echo them back with the leading title. Then redirect to a temp file. In case the command succeeds, then move the temp file into the original one.


With awk:

awk '{print "I have a", $0}' file > tmp_file && mv tmp_file file

With sed: check anubhava's answer for the best way. This can be another.

sed -i.bak -n 's/^/I have a /p' file

Note it is good practice to use -i.bak (or -i.whatever) to generate a backup file with the .bak extension.


Just for fun, you can also use paste:

$ paste -d" " <(printf "%0.sI have a\n" $(seq $(wc -l <file))) file
I have a dog
I have a cat

Explanation

  • paste -d" " file1 file prints two files side by side, with space as delimiter.
  • printf "%0.sI have a\n" $(seq $(wc -l <file)) print "I have a" as many times a lines file has.

    $ wc -l <a
    2
    $ seq $(wc -l <a)
    1
    2
    $ printf "%0.sI have a\n" $(seq $(wc -l <a))
    I have a
    I have a
    
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • +1 for such a complete answer to such a question. – Kent Jun 03 '14 at 15:37
  • 1
    I suggest not calling the variable `word` in `while read word`, because in the general case it doesn't just read a single word. Generally, adding `-r` to prevent `read` from interpreting the input is also a good idea. – mklement0 Jun 04 '14 at 06:49
  • @mklement0 fair enough, just changed it to `line` so it is more clear what does it catch. Also, regarding `-r`, I know see in `man bash` that `-r --> Backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not be used as a line continuation.`. Thanks for both! – fedorqui Jun 04 '14 at 09:26
1
sed -i 's/^/I have a /' your_file
pacholik
  • 8,607
  • 9
  • 43
  • 55