user2334436
user2334436

Reputation: 939

Sed Insert a newline before match

I'm trying to insert a string in multiple text files at a random line number. before adding the string in the text files i want to add a newline.

For example, a text file has 4 paragraphs.

paragraph 1

paragraph 2

paragraph 3

paragraph 4

I want the output to be

paragraph 1

STRING

paragraph 2

paragraph 3

paragraph 4

My code is working fine, but its not adding the empty newline before the string.

$ for i in *.txt; do sed -i "$(shuf -n 1 -e 2 4 6)i \n\rSTRING \n\r" $i ; done

Upvotes: 1

Views: 325

Answers (1)

Thor
Thor

Reputation: 47099

The i command is actually i\, from the GNU manual:

'i\'
'TEXT'
     insert TEXT before a line.

So the backslash before the n is "eaten" by the i command. Add an extra backslash and it should work.

Upvotes: 1

Related Questions