Stacksatty
Stacksatty

Reputation: 191

Regex remove characters after space in each line

I have a text file with 50k lines like this

word1 1 23
word2 43 23
word3 197
word4

and need a way to make it look like this:

word1
word2
word3
word4

So I need a way to remove every character behind the first space in each line. How do I do this?

Upvotes: 1

Views: 4693

Answers (3)

ghoti
ghoti

Reputation: 46856

[ghoti@pc ~]$ cat input.txt 
word1 1 23
word2 43 23
word3 197
word4
[ghoti@pc ~]$ awk '{print $1}' input.txt 
word1
word2
word3
word4
[ghoti@pc ~]$ sed 's/ .*//' input.txt 
word1
word2
word3
word4
[ghoti@pc ~]$ cut -d\  -f1 input.txt 
word1
word2
word3
word4
[ghoti@pc ~]$ 

Upvotes: 3

Prody
Prody

Reputation: 5298

Multiple solutions.

Solution 1: Vim

Open the file in vim, then run:

:%s/\s.*//g

Solution 2: sed

sed "s/ .*//g" < input_file > output_file

Cannot do this on windows tho.

Solution 3: Excel/Calc/Numbers

Import the file in OpenOffice/MSOffice/etc.
You can set space as a delimiter.
But this is a slower and less fun. :)

Upvotes: 6

Eurig Jones
Eurig Jones

Reputation: 8543

I would suggest using excel, or a spreadsheet to do this instead if it's a one-off.

Just import a file, and set the delimiter as a space character. Then you can delete all but the first column and save again as a text file.

Upvotes: 1

Related Questions