3

I want to delete newlines after lines containing a keyword e.g. like modifiers private:,public: or protected: to fulfill our coding standard. I need a command line tool (Linux) for this, so please no Notepad++, Emacs, VS, or Vim solutions, if they require user interaction. So in other words I want to do a:

sed -i 's/private:\s*\n\s*\n/private:\n/g'

I've seen this question but was unable to extend it to my needs.

Community
  • 1
  • 1
math
  • 8,514
  • 10
  • 53
  • 61

2 Answers2

1

If I understand correctly, you want to remove empty lines which follow a line containing private:, public:, or protected:.

sed ':loop;/private:\|public:\|protected:/{n;/^$/d;Tloop}' inputfile

Explanation:

  • :loop create a label
  • /private:\|public:\|protected:/ will search for lines containing the pattern.
  • n;/^$/d will load the next line (n), check whether it is an empty line (/^$/), and if it is, delete the line (d).
  • Tloop branch to label loop if there was no match (line was not empty)

I am no sed guru, there might be more elegant ways to do this. There might also be more elegant ways to do this in awk, perl, python, whatever.

Lesmana
  • 25,663
  • 9
  • 82
  • 87
  • Yes, thanks but it does not work on the same example where two modifiers are on two consecutive lines followed by an empty line. Same problem as above, since if sed fetches the next line, this line is never visited again. But your solution looks nicer than mine so far :D – math Dec 12 '11 at 19:03
  • Edited my answer. The sed command should now also cover the cases you mentioned. – Lesmana Dec 12 '11 at 19:27
  • Great and I got it working with perl: `perl -0777 -pi -e 's/([ \t\r]*)(private|protected|public):[ \t\r]*\n[ \t\r]*\n/$1$2:\n/g'`, thanks. BTW can your sed command also handle whitespace before and after the `private:` et al. modifiers? – math Dec 12 '11 at 19:40
  • As it stands now it will match all lines containing the keywords, regardless of any whitespace, or anything else for that matter, before or after the keyword. By clever regex manipulation you can make it match any pattern you want. – Lesmana Dec 12 '11 at 20:13
0
perl -0777 -pi -e 's/([ \t\r]*)(private|protected|public):[ \t\r]*\n[ \t\r]*\n/$1$2:\n/g' file

should do the trick, while also take trailing and leading whitespace into account, which I didn't specified in the question as this is not a must requirement.

math
  • 8,514
  • 10
  • 53
  • 61