Abhijeet Gulve
Abhijeet Gulve

Reputation: 869

How to add line at perticular line number for blank file using shell script

I'm having following data in file

Line 1

Now I have to add the three new lines at

line number 3,5,6

but when I use

sed -i '3i string1' file
sed -i '4i string2' file
sed -i '6i string3' file

it is not appending the data unless it having some lines in it.

but when that file is empty then it is not add the data as there is no line number which sed can find.

So how I can able to add this line in file.

Upvotes: 0

Views: 47

Answers (2)

anubhava
anubhava

Reputation: 785761

You can do:

# insert 5 blank lines into the file
printf "\n%.0s" {1..5} >> file

# now use sed to replace desired line numbers
sed -i '3s/^/string1/; 4s/^/string2/; 6s/^/string3/' file

Upvotes: 1

John1024
John1024

Reputation: 113934

To take any File and, if needed, add new lines to it as needed to make it at least n lines long:

awk -i inplace -v n=6 'END{for (i=NR;i<=n;i++) print""} 1' File # GNU awk

Or,

awk -v n=6 'END{for (i=NR;i<=n;i++) print""} 1' File >tmp && mv tmp File # BSD/OSX awk

If the file is already n lines long, this does nothing to the file.

After you have done this, your sed commands should work.

Upvotes: 0

Related Questions