PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, May 14, 2022

[FIXED] How to insert new lines after a specific empty line in linux?

 May 14, 2022     awk, linux, ubuntu     No comments   

Issue

I'm trying to find a way to insert a new line after a specific empty line.
for example I have a file contains firewall rules, and I want to insert new lines after "# ok icmp code for FORWARD" and first empty line. (I don't know the exact line number and it is different in multiple machines):

...

# ok icmp code for FORWARD
-A ufw-before-forward -p icmp --icmp-type destination-unreachable -j ACCEPT
-A ufw-before-forward -p icmp --icmp-type time-exceeded -j ACCEPT
-A ufw-before-forward -p icmp --icmp-type parameter-problem -j ACCEPT
-A ufw-before-forward -p icmp --icmp-type echo-request -j ACCEPT

[Insert new lines here]
# new lines comment
new line 1
new line 2

...

here is my incomplete solution:
to find the specific line number:

cat file.rules | grep -n "ok icmp code for FORWARD" | cut -d':' -f 1


to show the lines after specific line and before the empty line:

awk '!NF{f=0} /ok icmp code for FORWARD/ {f=1} f' file.rules

Solution

Using ed to edit the file:

ed -s file.rules <<'EOF'
/^# ok icmp code for FORWARD/;/^$/a
# new lines comment
new line 1
new line 2
.
w
EOF

First sets the current line to the one matching # ok icmp code for FORWARD, then advances the current line to the first blank line following that, and appends text after it (A line with a single period marks the end of input), then writes the changed file back to disk.



Answered By - Shawn
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing