| Newsgroups |
gmane.editors.sed.user |
| Message-ID |
<[email protected]> |
On 26/02/15 21:57, Thierry Blanc [email protected] [sed-users] wrote:
> On 26/02/15 11:12, Lars Noodén [email protected] [sed-users] wrote:
>> Using GNU sed 4.2.2-4ubuntu1 on Ubuntu 14.04 LTS GNU/Linux
>>
>>
>> I have some blocks of text spread over multiple lines and delimited by [
>> and ]. ( See the tail of the message for an example. ) I'd like to
>> delete the nth [ ] block. The following pattern will delete all [ ] blocks:
>>
>>
>> sed '/^\[$/,/^\]/d' in > out
>>
>>
>> That deletes more than I want deleted. How can I make a sed formula or
>> two that only deletes the nth block and leaves the others?
>>
>>
>> Regards,
>> /Lars
>>
>>
>> ###
>>
>>
>> foo
>> [
>> aaa
>> bbb
>> ccc
>> ]
>> [
>> ccc
>> bbb
>> aaa
>> ]
>> [
>> bbb
>> ccc
>> aaa
>> ]
>> [
>> bbb
>> aaa
>> ccc
>> ]
>> bar
>>
>>
>> ###
>>
>>
>> ------------------------------------
>> Posted by: =?UTF-8?B?TGFycyBOb29kw6lu?= <[email protected]>
>> ------------------------------------
>>
> An alternative is using grep, proably there's a more elegant grep
> version, but to start with:
>
> S=$(grep -n -m 3 "\[" file |sed -n '$s/:.*//p'); E=$(grep -n -m 3 "\]"
> file |sed -n '$s/:.*//p'); sed -r $S','$E'd' file
>
> use grep -m option to find the nth occurence of [ and ] ; put this
> number in a variable. use sed to delete from line number S to line number E.
>
>
>
>
> [Non-text portions of this message have been removed]
>
>
>
> ------------------------------------
> Posted by: Thierry Blanc <[email protected]>
> ------------------------------------
>
with interactive checking and sed instead of grep (does grep has an
option to just print the line number where a match is found and nothing
else?)
#!/bin/bash
BLOCK=$1
FILE=$2
S=$(sed -n "/\[/=" $FILE | sed -n $BLOCK'p')
E=$(sed -n "/\]/=" $FILE | sed -n $BLOCK'p')
sed -rn $S','$E'p' $FILE
read -p "delete block "
if [[ $REPLY == 'y' ]]
then
sed -ri $S','$E'd' $FILE
fi
[Non-text portions of this message have been removed]