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

376
Chris Rainey

В 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тот же результат?

0
You might be able to improve this question , there are loads of problems with it but we get the message " Chris Rainey is a new contributor. Be nice, and check out our Code of Conduct. https://superuser.com/conduct" So hopefully somebody can reply to you re that but it'd take me too long. barlop 5 лет назад 0

1 ответ на вопрос

0
simlev

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

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

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

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

И AWK:

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

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

sed -r '/^"set compatible/! s/^"(\S|\s)/\1/' /etc/vim/vimrc perl -lape 's/^"(\S|\s)/\1/ if!/^"set compatible/' /etc/vim/vimrc awk '!/^"set compatible/ {$0=gensub(/^"(\S|\s)/,"\\1",1)}1' /etc/vim/vimrc 

Похожие вопросы