Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having an extra characters error with sed when using curly braces or loops

I'm currently writing a batch script to read from and modify some configuration files in Windows. Thankfully, I have access to said, and as such I can use that for most of what I have to do, albeit with some quirks due to the environment.

The statement I'd like to execute is:

sed '/\[$/{:loop N /^^]/!b loop} s/\n//g'

Which should theoretically remove any newlines on lines between lines with square brackets. I'm using double carets here to escape and use the second one (a quirk of cmd.exe). However it fails with the following error:

sed: -e expression #1, char 15: extra characters after command

In testing some other other statements I've got the following results.

sed '/\[/{ s/.*//g }' – Executes exactly as it should

sed '/\[/{ N } s/.*//g' – Fails with sed: -e expression #1, char 11: extra characters after command

sed 's/^^ */^&\n/ :loop s/.*/asdf/ b loop' – Fails with sed: -e expression #1, char 12: unknown option tos'`

I'm just not sure whether my error with my main statement is due to me screwing up the syntax, or if it's just because I'm in Windows. Any thoughts or assistance you can provide would be wonderful.

like image 573
Evan Avatar asked Nov 23 '10 18:11

Evan


Video Answer


1 Answers

sed '/\[$/{:loop; N;/]$/!b loop}; s/\n//g'

You need to put semi-colons between your statements. Also, I used the '$' anchor instead of '^' because you'll never match '/^]/' because your 'N' command alters the pattern space to have stuff before the '['. Remember, '/ /' matches against the pattern space, not the current input line.

Test

$ echo -e 'A\n[\nfoo\nbar\nbaz\n]\nB' | sed '/\[$/{:loop; N;/]$/!b loop}; s/\n//g'
A
[foobarbaz]
B
like image 176
SiegeX Avatar answered Oct 12 '22 23:10

SiegeX