Substituting everything from = to end of the line in VIM - vim

Let's say I have several lines like:
$repeat_on = $_REQUEST['repeat_on'];
$opt_days = $_REQUEST['opt_day'];
$opt_days = explode(",", $opt_days);
... and so on.
Let's say I use visual mode to select all the lines: how can I replace everything from = to the end of the line so it looks like:
$repeat_on = NULL;
$opt_days = NULL;
$opt_days = NULL;

With the block selected, use this substitute:
s/=.*$/= NULL;
The substitution regex changes each line by replacing anything between = and the end of the line, including the =, with = NULL;.
The first part of the command is the regex matching what is to be replaced: =.*$.
The = is taken literally.
The dot . means any character.
So .* means: 0 or more of any character.
This is terminated by $ for end of line, but this actually isn't necessary here: try it also without the $.
So the regex will match the region after the first = in each line, and replace that region with the replacement, which is = NULL;. We need to include the = in the replacement to add it back, since it's part of the match to be replaced.
When you have a block selected, and you hit : to enter a command, the command line will be automatically prefixed with a range for the visual selection that looks like this:
:'<,'>
Continue typing the command above, and your command-line will be:
:'<,'>s/=.*$/= NULL;
Which will apply the replacement to the selected visual block.
If you'll need to have multiple replacements on a single line, you'll need to add the g flag:
:'<,'>s/=.*$/= NULL;/g

Some alternatives:
Visual Block (fast)
On the first line/character do... Wl<C-v>jjCNULL;<Esc>bi<Space><Esc>
Macro (faster)
On the first line/character do... qqWllCNULL;<esc>+q2#q
:norm (fastest)
On the first line do... 3:no<S-tab> WllCNULL;<Enter>
Or if you've visually selected the lines leave the 3 off the beginning.

Related

Vim delete parent parenthesis and reindent child

I'm trying to go from here:
const f = function() {
if (exists) { // delete this
const a = 'apple'
}
}
to:
const f = function() {
const a = 'apple'
}
What's the fastest way to delete and reindent everything in between?
Assuming that cursor is inside the braces; any number of lines and nested operators; "else"-branch is not supported:
[{"_dd<]}']"_dd
Explanation:
[{ go to previous unmatched brace
"_dd delete the "{"-line (now the cursor is in the first line of the block)
<]} decrease identation until the next unmatched "}"
'] go to the last changed line (i.e. "}"-line)
"_dd and delete it
If the cursor is initially set on the "{"-line and you don't care for 1-9 registers, the command can be simplified to dd<]}']dd
Assuming your cursor is somewhere on the line containing const a
?{^M%dd^Odd== (where ^M is you hitting the Enter key and ^O is you hitting Ctrl+O).
Broken down this is:
?{^M - search backwards/upwards for the opening brace
% - jump to the corresponding brace (closing brace)
dd - delete the current line
^O - jump to previous location (the opening brace)
dd - delete the line
== - indent current line
You don't need a special macro or function or anything to do this since vim gives you all the powerful text manipulation tools to do the task. If you find yourself doing this an awful lot then you could always map it to a key combination if you want.
The above only works for single lines inside curly braces, but the one below will work for multiple lines (again assuming you are on some line inside the curly braces)
<i{0f{%dd^Odd I'll leave you to figure out how this one works. Type the command slowly and see what happens.
Great answers all around, and, as pointed out, you can always map these keys to a shortcut. If you'd like to try a slightly more generic solution, you could check my "deleft" plugin: https://github.com/AndrewRadev/deleft.vim

How to extract word from a sentence in Linux Shell?

I have a shell file with the below SQL statements in it:
SELECT distinct vpi.pin_id_e
FROM MSSINT.V_DSLAMS vd,
MSSINT.v_pin_inventory_old vpi
where vd.dslam like '%#%'
and vd.dslam_id = vpi.dslam_id ;
select pa.circuit_design_id,pa.node_address,c.exchange_carrier_circuit_id,c.type,c.rate_code,c.status
from ASAP.port_address pa,
asap.circuit c
where pa.equipment_id = 4561233 and pa.circuit_design_id is not null
and pa.circuit_design_id = c.circuit_design_id;
In the above content of my shell file, I have to extract the table or view names alone (those between from and where keywords).
I have seen a lot of suggestions to get words based on position, but I don't want those since they will not work like between operators.
awk 'toupper($0) ~ /^FROM/ { getline;flag=1 } toupper($0) ~ /^WHERE/ { flag=0 }flag' filename
With awk, convert the string to upper case and then pattern match against FROM at the beginning of the line. If this exists, read in the next line and set flag to one. When WHERE is encountered at the beginning of the line, set the flag equal to 0. The complete line will then only print when flag is set to one i.e. between the from and where lines

Select first word from each line in multiple lines with Vim

I would like to copy the first words of multiple lines.
Example of code :
apiKey := fmt.Sprintf("&apiKey=%s", args.ApiKey)
maxCount := fmt.Sprintf("&maxCount=%d", args.MaxCount)
id := fmt.Sprintf("&id=%s", args.Id)
userid := fmt.Sprintf("&userid=%s", args.Userid)
requestFields := fmt.Sprintf("&requestFields=%s", args.RequestFields)
I would like to have this in my clipboard :
apiKey
maxCount
id
userid
requestFields
I tried with ctrl-v and after e, but it copies like on the image :
You could append every first word to an empty register (let's say q) using
:'<,'>norm! "Qyiw
That is, in every line of the visual selection, execute the "Qyiw sequence of normal commands to append (the first) "inner word" to the q register.
You need to have > in cpoptions for the newline to be added in between yanks (:set cpoptions+=>), otherwise the words will be concatenated on a single line.
If you want to quickly empty a register you can use qqq in normal mode (or qaq to empty register a).
Note: the unnamed register ("") will also contain what you want at the end of the operation, so you don't need to "qp to paste it, p will do.
I think the chosen answer is a really good one, the idea of appending matches to registers can be pretty useful in other scenarios as well.
That said, an alternative way to get this done might be to align the right-hand side first, do the copying and then undo the alignment. You can use a tool like tabular, Align or easy-align.
With tabular, marking the area and executing :Tab/: would result in this:
apiKey : = fmt.Sprintf("&apiKey=%s", args.ApiKey)
maxCount : = fmt.Sprintf("&maxCount=%d", args.MaxCount)
id : = fmt.Sprintf("&id=%s", args.Id)
userid : = fmt.Sprintf("&userid=%s", args.Userid)
requestFields : = fmt.Sprintf("&requestFields=%s", args.RequestFields)
You can now use visual block mode to select the first part, and then use u to undo the alignment.
Relying on the external cut program:
:'<,'>!cut -d' ' -f1

Add a number of '=' in a rest (reStructuredText) document that equals to characters from last line?

I want to use a shortcut to add needed = (from Section/Title reStructuredText syntax) according to the last line.
So, suppose (being | the cursor position)
Title
|
and pressing an specific mapping mapped to a function, add a number of = that equals to the last line (where Title is), becoming:
Title
=====|
This sequence will get you close:
kyyp:.s/./=/g
Duplicate the previous line, then in that line, change every character to an equals sign. Map that to a key sequence you like, and try it out.
Another way:
:execute "normal " . strlen(getline(line(".") - 1)) . "i="
strlen(getline(line(".") - 1)) returns the lenght of the line above the current position. The result is that the command Ni= is executed, inserting = N times.
For a mapping I would have used:
put=repeat('=', col('$')-1)
For something more interactive, I would have use the same solution as Ned's.
(I don't like my mappings to change the various registers like #" or #/)
My vim-rst-sections vim plugin will convert lines to section headings:
http://www.vim.org/scripts/script.php?script_id=4486
In your case, you'd put the cursor on the line, and type <leader><leader>d to get a top-level heading like this:
#####
Title
#####
A few repeats of <leader><leader>d will take you down to the standard hierarchy of Python ReST sections to the =.

Copy matching text to register

does anyone know if it is possible to concatenate matches resulting from a search into a single register? E.g, I have a file with following contents:
aaa :xxx 123
bb :y 8
ccccc :zzzzz 1923
Now what I want is to copy column starting with ':' somewhere else. Unfortunatelly I can't use visual block mode, because the first column hasn't fixed width.
I thought that I could search for the second column (:\w+) and store the maches into a register.
Another way:
:g/:/norm f:"Aye
Per :h quote_alpha, if you use an uppercase register name, it appends rather than replaces the contents of the register. If you run this and check the contents of register "a, you'll see
:xxx:y:zzzzz
(Possibly with linebreaks, depending on how you have cpoptions set.)
You could make a macro:
qa (make a macro and store it in register a).
"Rye (yank to end of word and append it to register r - capital means append, lowercase overwrite.)
n (next match)
q (end recording)
If there are 10 matches, do 10#a
Make sure register r is empty when you begin.
Add this to your .vimrc or create any file in the vim plugin folder with the following content.
After you execute this lines through .vimrc or plugin, use :CopyTextAfterColon command and then simply insert from the system buffer text you need.
function! s:copy_after_colon()
let values = ''
let pattern = '^.*:\(\w\+\).*$'
for line_number in range(1, line('$'))
let line = getline(line_number)
if line =~ pattern
let value = substitute(line, pattern, '\1', '')
let values .= value."\n"
endif
endfor
let #* = values
endfunction
command! -nargs=0 CopyTextAfterColon call <SID>copy_after_colon()
You can adapt this later for different purposes.
I would first start with parsing the file. For this use TextFieldReader rather than inventing your own CSV parser:
using Microsoft.VisualBasic.FileIO;
TextFieldParser reader = new TextFieldReader("C:\MyFile.txt");
reader.Delimiters = new string[] { " " };
string[] currentRow = null;
while (!reader.EndOfData)
{
try
{
currentRow = reader.ReadFields();
foreach(string field in currentRow)
{
//save this field...
}
}
catch (MalformedLineException ex)
{
//handle exception the way you want
}
}
Once I have the data I would extract just the column that I am interested in. If you can assume that each line has the same pattern then you can figure out the right column during parsing the first row and then while parsing the rest of the rows you can just save the appropriate column. You don't have to save the whole file into the memory.
EDIT: I am terribly sorry, I thought the question was about C# programming. My mistake - sorry.

Resources