Showing posts with label pattern. Show all posts
Showing posts with label pattern. Show all posts

Tuesday, January 14, 2014

Removing Lines that Don't Match a Pattern

Following up on a previous tip, you can also use the "g" and "d" commands to remove lines in your current buffer that don't match a specific pattern. The following example would remove all lines that don't match "www.example.com".
:g!/www\.example\.com/d

Friday, October 30, 2009

Handy Shell Pattern

When piping commands, you can often benefit from breaking your data into multiple lines. A combination of sed and xargs can make this very easy to do. Take the following commands for example:

cd /tmp && mkdir blah && cd blah;
touch file-1 file-2 file-3;
ls | sed 'p; s/-//' | xargs -n2

Breaking this down, we create a directory and touch three empty files. From there, we use sed to print two lines. The first line is the original file name, the second line is the filename without the dash. From here, we can use the -n argument in conjunction with xargs to merge the two lines back into a single line. The resulting output would be:

file-1 file1
file-2 file2
file-3 file3

Once you have the lines joined, you could do something like:

... | while read a b; do mv $a $b; done

Bonus tip: the "read" bash builtin takes a line and associates each word with a given variable. Type "help read" from the shell for the complete documentation.

In summary the full command-chain for this tip would be:

cd /tmp && mkdir blah && cd blah;
touch file-1 file-2 file-3;
ls | sed 'p; s/-//' | xargs -n2 | while read a b; do mv $a $b; done

Thanks to Chris Sutter for contributing this handy shell pattern, and thanks to Andeers for the coffee!

Tuesday, March 10, 2009

Change Last, First to First Last

Here's a tip borrowed from the Vim help file. Say that you have a list of names like:

Doe, John
Smith, Peter

and you want to change that to:

John Doe
Peter Smith

You can use the following substitute pattern to easily do so:

:%s/\([^,]*\), \(.*\)/\2 \1/

Basically, you're capturing zero or more NOT commas followed by a comma and space and then capturing zero or more of anything. The comma and space are outside the parens, so they're not stored. The parens store the captured groups in the special variables \1, \2, \3, \N from left to right, so the replacement pattern is substituting in the groups in the reverse order they were captured.

Wednesday, March 5, 2008

Delete Lines Matching Keyword

Neat little trick using the global ex command to remove all lines matching a given pattern.

:g/.*foo.*/d

Of course you can use any ex command at the end and you can put in whatever pattern you'd like.