Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove all characters after pattern in text file

Tags:

regex

vim

I have a text file with thousands of lines of text. Each line ends like

\\server\share\file.txt -> information

I want to remove everything following the space after the end of the file extension. So everything after " ->" (there's a space after the first quote)

How would you do this? I'd like to use vim as I am trying to understand more about it, but any program will do; I'd like to get this done soon.

like image 718
AaronJAnderson Avatar asked Apr 26 '11 13:04

AaronJAnderson


People also ask

How do I delete everything after a character in Bash?

In Bash (and ksh, zsh, dash, etc.), you can use parameter expansion with % which will remove characters from the end of the string or # which will remove characters from the beginning of the string. If you use a single one of those characters, the smallest matching string will be removed.

How do I remove a specific pattern from a Unix file?

N command reads the next line in the pattern space. d deletes the entire pattern space which contains the current and the next line. Using the substitution command s, we delete from the newline character till the end, which effective deletes the next line after the line containing the pattern Unix.


1 Answers

Your description is contradictory.

  1. "everything following the space after the end of the file extension"
  2. "So everything after " ->" (there's a space after the first quote)"

Did you want to keep the arrow or not?

1 is simply accomplished with:

:%s/ ->.*/

and actually if you really did want to keep the space before the arrow, like you said, it would be:

:%s/ ->.*/ /

2 can be done with:

:%s/\( ->\).*/\1/

If you prefer to view the results of your search before the replace you can build your search first using /:

/\( ->\).*

This will highlight all results to make sure you are replacing the right thing. You can then execute the replace command with an empty search term to use the last search (the stuff thats highlighted).

:%s//\1/
like image 190
Tommi Kyntola Avatar answered Sep 20 '22 06:09

Tommi Kyntola