I have a text file that has many groupid = []. I wan't to edit the specific line which is 41, How can I do it?
My command: sed -i "s/groupid = []/groupid = [ 2 ]/" rights.toml
I have tried:
sed -i "s@groupid = []@groupid = [ 2 ]@" rights.toml
sed -i -e "s@groupid = []@groupid = [ 2 ]@g" "rights.toml"
sed -i "41 s/groupid = []/groupid = [ 2 ]/g" rights.toml
sed -i "41,s/groupid = []/groupid = [ 2 ]/g" rights.toml
sed -i "41s/groupid = []/groupid = [ 2 ]/g" rights.toml 1 Answer
The problem with your sed command
s/groupid = []/groupid = [ 2 ]/is that [ and ] are special characters on the LHS of a substitute command, so it's interpreting
]/groupid = [ 2 as a set of characters to match after groupid = . Since that "eats" the first /, your command looks like s/pattern/ instead of s/pattern/replacement.
At a minimum, you need to escape the opening [ to make it literal - I'd probably escape the closing ] as well to make the intent clear:
sed "s/groupid = \[\]/groupid = [ 2 ]/" rights.tomlYou can add an address to specify a particular line
sed "41s/groupid = \[\]/groupid = [ 2 ]/" rights.tomlhowever your file doesn't appear to have a groupid on line 41. As an aside, I'd recommend using ' ' single quotes rather than double quotes around sed expressions unless you explicitly need to perform shell expansions within them.
HOWEVER you should really consider using a TOML aware tool rather than sed if your text is TOML. For example, using yq: Command-line YAML/XML/TOML processor - jq wrapper for YAML, XML, TOML documentsin TOML mode:
tomlq -t '.rule[0].groupid |= [2]' rights.toml(again, it's not clear whether you want to modify rule[0] or rule[1] since line 41 doesn't appear to contain a groupid).