Как использовать sed для удаления "(двойные кавычки) в строках кода, оставляя их в реальных строках комментариев в файле vimrc?


0

В Ubuntu (сервер / рабочий стол) я хочу удалить один "(двойные кавычки) символ из начала строк в моем /etc/vim/vimrc.

Это должно быть сделано для всех строк, которые начинаются с a ", но не в том случае, если за "ним следует один пробел, поскольку последние указывают на реальные комментарии (в отличие от прокомментированного кода). Моя цель состоит в том, чтобы переключать закомментированный код, удаляя начальный ", оставляя остальную часть файла без изменений.

ДО:

" Vim will load $VIMRUNTIME/defaults.vim if the user does not have a vimrc.
" This happens after /etc/vim/vimrc(.local) are loaded, so it will override
" any settings in these files.
" If you don't want that to happen, uncomment the below line to prevent
" defaults.vim from being loaded.
" let g:skip_defaults_vim = 1

" Uncomment the next line to make Vim more Vi-compatible
" NOTE: debian.vim sets 'nocompatible'.  Setting 'compatible' changes numerous
" options, so any other options should be set AFTER setting 'compatible'.
"set compatible

" Vim5 and later versions support syntax highlighting. Uncommenting the next
" line enables syntax highlighting by default.
if has("syntax")
  syntax on
endif

" If using a dark background within the editing area and syntax highlighting
" turn on this option as well
"set background=dark

" Uncomment the following to have Vim jump to the last position when
" reopening a file
"if has("autocmd")
"  au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
"endif

ПОСЛЕ:

" Vim will load $VIMRUNTIME/defaults.vim if the user does not have a vimrc.
" This happens after /etc/vim/vimrc(.local) are loaded, so it will override
" any settings in these files.
" If you don't want that to happen, uncomment the below line to prevent
" defaults.vim from being loaded.
" let g:skip_defaults_vim = 1

" Uncomment the next line to make Vim more Vi-compatible
" NOTE: debian.vim sets 'nocompatible'.  Setting 'compatible' changes numerous
" options, so any other options should be set AFTER setting 'compatible'.
"set compatible

" Vim5 and later versions support syntax highlighting. Uncommenting the next
" line enables syntax highlighting by default.
if has("syntax")
  syntax on
endif

" If using a dark background within the editing area and syntax highlighting
" turn on this option as well
set background=dark

" Uncomment the following to have Vim jump to the last position when
" reopening a file
if has("autocmd")
  au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
endif

DIFF:

~$ diff BEFORE.out AFTER.out 
21c21
< "set background=dark
---
> set background=dark
25,27c25,27
< "if has("autocmd")
< "  au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
< "endif
---
> if has("autocmd")
>   au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
> endif

Обратите внимание, что при наличии кода с отступом после запуска "следует число пробелов, превышающее один: я хочу также раскомментировать эти строки, сохраняя отступ.

Я понял, как заставить все работать с помощью следующей команды:

$ sudo sed -i.orig '/^\" [a-zA-Z]\|^"set compatible\|^\" let g:skip_defaults_vim = 1b/! s/^\"//' /etc/vim/vimrc

Можно ли сделать это лучше (чище / плотнее / и т.д.)?

Можно ли это сделать, используя awkдля того же результата?


Возможно, вам удастся улучшить этот вопрос, есть множество проблем с ним, но мы получаем сообщение «Крис Рейни - новый участник. Будьте внимательны и ознакомьтесь с нашим Кодексом поведения. Superuser.com/conduct » Так что, надеюсь, кто-нибудь сможет ответить вам, но это займет у меня слишком много времени.
Barlop

Ответы:


0

Команда замещения очень проста:

sed -r 's/^"(\S|\s{2,})/\1/' /etc/vim/vimrc

Или аналогично в Perl:

perl -lape 's/^"(\S|\s{2,})/\1/' /etc/vim/vimrc

И AWK:

awk '{$0=gensub(/^"(\S|\s{2,})/,"\\1",1)}1' /etc/vim/vimrc

В вашем примере вы указываете исключения для строк, содержащих определенные строки.
Это не объясняется в вашем тексте, но может быть добавлено как условие:

sed -r '/^"set compatible/! s/^"(\S|\s{2,})/\1/' /etc/vim/vimrc
perl -lape 's/^"(\S|\s{2,})/\1/ if!/^"set compatible/' /etc/vim/vimrc
awk '!/^"set compatible/ {$0=gensub(/^"(\S|\s{2,})/,"\\1",1)}1' /etc/vim/vimrc
Используя наш сайт, вы подтверждаете, что прочитали и поняли нашу Политику в отношении файлов cookie и Политику конфиденциальности.
Licensed under cc by-sa 3.0 with attribution required.