Rahul
Rahul

Reputation: 63

How to add a line in multiple files in unix

I want to add a common plain text line to all the files present in same Unix directory.And i want to add this above a specific keyword present in all the files and save it using !wq.

i did try the below script but i am able to add only one line or one word above a specific keyword, i need to add multiple lines above this

for i in *; 
do sed -i 's/KEYWORD/datatoinsert\nKEYWORD/' "$i";
done

Any help is appreciated, even if someone has tried this in Python i would like to try that as well.

Upvotes: 2

Views: 6819

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84579

There is no loop needed, you can add the 'plain text' line with a simple sed edit in place, e.g.

$ sed -i '/keyword/s/^/plain text\n/' *

Example Files

$ cat file1.txt
word
keyword
rest

Example Use/Changes

$ sed -i '/keyword/s/^/plain text\n/' *
$ cat file1.txt
word
plain text
keyword
rest

Where you can break down the sed command as

  • sed -i edit the files in place

  • /keyword/ locate line containing keyword

  • s substitute command, e.g s/find/replace/

  • ^ match the beginnng of line

  • plain text\n the replace text

So you essentially find the beginning of the line containing keyword and replace (insert) the text plain text\n containing its own newline there.

Upvotes: 5

npit
npit

Reputation: 2359

With bash and sed, adding the contents of replacement before the keyword dog:

$ cat test.sh
#!/usr/bin/env bash
replacement="cats\neverywhere"
sed  "s/dog/$replacement\ndog/g" "$1"

Examples:

$ cat f1
one
two
dog
three

$ ./test.sh f1
one
two
cats
everywhere
dog
three

$ cat f2
dog
so close
no matter
dog
far
dog

$ ./test.sh f2
cats
everywhere
dog
so close
no matter
cats
everywhere
dog
far
cats
everywhere
dog

Upvotes: 0

Related Questions