Delete last occurrence} from file

I am trying to use sed to remove the last occurrence} from a file. So far I have this:

sed -i 's/\(.*\)}/\1/' file

But this removes as many} as at the end of the file. Therefore, if my file looks like this:

foo
bar
}
}
}

this command will remove all 3 of the characters}. How can I limit this to just the last attachment?

+1
source share
5 answers

sed is a great tool for simple single-line replacements. For anything, just use awk, for example. with GNU awk for gensub () and multi-char RS:

$ cat file1
foo
bar
}
}
}
$
$ cat file2
foo
bar
}}}
$
gawk -v RS='^$' -v ORS= '{$0=gensub(/\n?}([^}]*)$/,"\\1","")}1' file1
foo
bar
}
}
$
$ gawk -v RS='^$' -v ORS= '{$0=gensub(/\n?}([^}]*)$/,"\\1","")}1' file2
foo
bar
}}
$

, } char , , , , , , } ( , sed ), \n? RE:

$ gawk -v RS='^$' -v ORS= '{$0=gensub(/}([^}]*)$/,"\\1","")}1' file1
foo
bar
}
}

$

tmp , -i inplace:

$ gawk -i inplace -v RS='^$' -v ORS= '{$0=gensub(/}([^}]*)$/,"\\1","")}1' file1
$ cat file1
foo
bar
}
}

$
+3

-

sed -i '1h;1!H;$!d;g;s/\(.*\)}/\1/' file

, , awk.

+7

:

awk  'BEGIN{file=ARGV[1]}{a[NR]=$0}/}/{skip=NR}END{for(i=1;i<=NR;++i)if(i!=skip)print a[i]>file}' file
0

thnks @jthill 1

sed ':a
$ !{N
    ba
    }
$ s/}\([^}]*\)$/\1/' YourFile

. , }

0
source

When I read "I am doing something with the last ...", I think: "Cancel the file, do something with the first ..., flip the file"

tac file | awk '!seen && /}/ {$0 = gensub(/(.*)}/, "\\\1", 1); seen = 1} 1' | tac
0
source

All Articles