0

I have a code:

1 /**             
2 a        b         c
3 **/
4 int main() {
5     int x;
6     if ( condition) {
7     return       x;
8     }
9 }

I need to change multiple whitespaces between tokens or strings to single whitespace eg in line 7 but comments (line 2) should not be affected nor the leading tabs in the code. So, the output should be:

1 /**             
2 a        b         c
3 **/
4 int main() {
5     int x;
6     if ( condition) {
7     return x;
8     }
9 }

I tried using 'tr': ~$ tr -s " " < file but it changed line 2 as well as removed leading tabs in line 5 to line 8. Can it be done using sed?

  • 2
    Parsing C comments is the hard part here. – ilkkachu Sep 24 '18 at 4:33
  • I think it will have to be greedy like cat input | sed 's/(return)( *)(x)/\1 \3/g' > output – MelB Sep 24 '18 at 4:43
  • What should happen with printf("some spacey words\n"); where the words have more than one space between them? (the markup here removes the multiple spaces between the words). – Kusalananda Sep 24 '18 at 6:31
  • 3
    I think you'd be better off with using a proper C code formatter such as indent or clang-format. – Kusalananda Sep 24 '18 at 6:35
0

How far would

sed -rn '\#/\*\*#,\#\*\/*# {p;b}; s/([^ ]) +/\1 /g; p' file

get you? It prints the comment lines unmodified (can't deal with comment on / off in the same line, though) and skips the rest of the script. For uncommented lines, it squeezes any multiple spaces following a non-space char (so line indentation is out of scope) to a single space.

  • great, worked ! An explanation would be better. – MelB Sep 26 '18 at 11:29
0

Finally, this worked for me:

sed -i 's/\([a-zA-Z]\+\)\( *\)\([a-zA-Z]\+\)/\1 \3/g' $1

  • This doesn't seem to leave the comments alone? – RudiC Sep 26 '18 at 13:45
  • but in mine it does, I dont know how. I had a deadline so this worked. – MelB Sep 27 '18 at 7:19

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.