简体   繁体   中英

remove the last occurrence of } from a file

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

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

But this removes as many } as there are on the end of the file. So if my file looks like this:

foo
bar
}
}
}

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

someone game me this as a solution

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

I'm just not sure it's as good as the above awk solution.

sed is an excellent tool for simple substitutions on a single line. For anything else, just use awk, eg 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
}}
$

Note that the above will remove the last } char AND a preceding newline if present as I THINK that's probably what you would actually want but if you want to ONLY remove the } and leave a trailing newline in those cases (as I think all of the currently posted sed solutions would do), then just get rid of \\n? from the matching RE:

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

$

And if you want to change the original file without manually specifying a tmp file, just use the -i inplace argument:

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

$

使用缓冲区,您可以直接修改文件:

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

thnks to @jthill for remark for the 1 line file issue

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

Need to load the file in buffer first. This does not remove the new line if } is alone on a line

当我阅读“对最后一个 ...执行某项操作”时,我认为“反转文件,对第一个 ...进行某些操作,重新反转文件”

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM