Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed to remove everything after "." in file using * command?

Tags:

bash

sed

I have the following data.txt:

 95 flour.
 47 water.s
 etc..

I need to remove everything after the period (.) in the file to yield something like this:

 95 flour
 47 water
 etc..

I have tried the using these sed commands without success, which yield a blank document:

sed "s/'.*//" data.txt > cleaned.txt 
sed 's/\.*//' data.txt > cleaned.txt 
like image 765
Novice Avatar asked Sep 03 '13 22:09

Novice


People also ask

Can we delete content in a file by using sed command?

There is no available to delete all contents of the file. How to delete all contents of the file using sed command.

How can I remove all text 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 can I replace text after a specific word using sed?

Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.


2 Answers

Either escape the . with a backslash to get a literal ., or use brackets to define a character class:

sed 's/\..*$//' data.txt > cleaned.txt
sed 's/[.].*$//' data.txt > cleaned.txt

You tried 's/\.*//', which is "zero or more literal dots", which is different from "literal dot followed by zero or more of anything", i.e. 's/\..*//'. I also added a $ for good measure.

like image 133
Adam Rosenfield Avatar answered Oct 23 '22 17:10

Adam Rosenfield


This is the simplest:

sed "s/\..*//"

And this is, I think, one of the best ways of doing it (better than pure bash or Python).

like image 30
MK. Avatar answered Oct 23 '22 18:10

MK.