0

The following command will add pattern to the fourth line.

sed -i '4i pattern' file

But it is not working if I have less than four lines in the file. The requirement is I need to add the pattern in 4th line with empty prefix lines.

Expected Result: cat -n file

1  line1
2
3
4  pattern

GNU sed version 4.2.1

1

You can pad the file with a few blank lines to ensure there are at least 4 lines:

{ cat file; echo; echo; echo; } | sed -e '4i pattern' 

If you want to subsequently trim the trailing blank lines, then you can pipe that into:

| sed -n 'H; ${g; s/^\n//; s/\n\+$//; p}' 

or

| tac | awk '/./{p=1}p' | tac 

Or adding only the minimum number of blank lines:

{ cat file; for ((i=$(wc -l <file); i<3; i++)); do echo; done; } | sed '3a pattern'

Note the sed program changed to append after line 3 instead of insert before line 4.

| improve this answer | |
  • Thanks. It is possible to make echo dynamic. if we don't know the number of lines exist in the file. as title suggests – Stack EG Sep 7 '18 at 13:26
1
while [ $(wc -l <file) -lt 4 ] ; do
    echo >> file
done
sed -i '4i pattern' file
| improve this answer | |
0

Check if file has enough lines with wc -l (counting lines).

Display a warning if file has not enough lines.

[ $(cat file | wc -l) -ge 4 ] && sed -i '4s pattern' file || echo "not enough lines"
| improve this answer | |
  • Be careful with the A && B || C pattern: if B exits with non-zero, C will be executed. – glenn jackman Sep 7 '18 at 12:49
  • @Michael D want to add the pattern in 4th line even it has less the 4 lines. If previous line is blank also not a problem. – Stack EG Sep 7 '18 at 12:50
  • @glennjackman please check my edit in question. – Stack EG Sep 7 '18 at 12:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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