Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running AWK in Vim's search

Tags:

vim

awk

How can you run AWK in Vim's selection of the search?

My pseudo-code

%s/!awk '{ print $2 }'//d

I am trying to delete the given column in the file.

like image 401
Léo Léopold Hertz 준영 Avatar asked Dec 19 '09 23:12

Léo Léopold Hertz 준영


People also ask

Can we use awk in TCL?

Awk is perfectly usable from Tcl, as is sed — and sometimes that's the easiest way to do things — but you have to remember that Tcl's syntax is not the same as that of a normal Unix shell. Why does Tcl use braces instead of single quotes?

Can we use awk in shell script?

Awk is an excellent tool for building UNIX/Linux shell scripts. AWK is a programming language that is designed for processing text-based data, either in files or data streams, or using shell pipes. In other words you can combine awk with shell scripts or directly use at a shell prompt.

What is awk F command?

For example: awk –F":" '{ print $3 }' file.dat. indicates that the given data file uses colon ( : ) characters to separate record fields. The –F option must come before the quoted program instructions. awk also allows you to define the value of variables on the command line by using the –v option.


2 Answers

Though they probably address the issue of the original poster, none of the answer addresses the issue advertised in the title of the question. My proposal to remove the first line of the question and to retitle it as "Deleting one column in vim" having been unanimously rejected, here is a solution for people arriving there by actually looking for that.

Deleting a column (here the second one, as in OP's pseudocode example) with awk in vim :

:%!awk '{$2=""; print $0}'

Of course, it also works for a portion of the file — e.g. for lines 10 to 20 :

:10,20!awk '{$2=""; print $0}'

As for "[running] awk in Vim's selection of the search", not sure you can exactly do that but anyway the search and substitution is an easy job for awk, if not its primary purpose. The following replaces "pattern" with "betterpattern" in the second column if it matches :

:%!awk '$2~"pattern" {gsub("pattern","betterpattern",$2)}

Note that the NOT operator requires escaping (\! instead of !). The following replaces the value in the second column by its increment by 10 if it matches "number" and let other lines unchanged :

:%!awk '$2~"number" {gsub($1,$1+10)} $2\!~"number" {print $0}'

Appart from this point it's just awk syntax.

like image 190
Skippy le Grand Gourou Avatar answered Nov 07 '22 20:11

Skippy le Grand Gourou


In command mode, press Ctrl-v to go into visual mode, then you can block-select the column using cursor movement keys. You can then yank and put it or delete it or whatever you need using the appropriate vim commands and keystrokes.

like image 20
Dennis Williamson Avatar answered Nov 07 '22 18:11

Dennis Williamson