Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a file in which I need to eliminate everything after the first ; on every line.

So a file like this:

sdfsdsdf;
fsdfsddf;sdfsd;

Will result in this:

sdfsdsdf
fsdfsddf

I have looked into grep and sed. I would appreciate an answer incorporating either of these commands.

share|improve this question

4 Answers 4

up vote 3 down vote accepted

sed is probably easiest and faster than awk or perl in this circumstance:

sed 's/^\([^;][^;]*\);.*$/\1/' some_file_name
share|improve this answer
5  
This is more complicated than it should be! sed 's/;.*//' –  Gilles Aug 23 '10 at 20:43
    
I beg to differ. perl -pe 's/;.*//' some_file_name is just as easy, and arguably up to 1500% faster when operating in large files. –  codehead Aug 24 '10 at 3:59
    
I have several systems where sed is available but perl is not, so I encourage using lighter-weight solutions where they suffice. –  dubiousjim Apr 19 '12 at 21:06

another option is to use the cut command

cat a.file | cut -d';' -f1
share|improve this answer
8  
useless us of cat –  hop Aug 23 '10 at 18:35

I typically use awk for things like this:

cat a.file | awk -F=";" '{ print $1 }'

That will take each line of a file and print the first group before the delimiter -F

share|improve this answer
5  
useless use of cat. –  Dennis Williamson Aug 24 '10 at 1:18
    
Second Dennis there. And under linux and BSD that -F=";" does not work as intended. And you might want to quote that $1, too: awk -F";" '{print $1}' a.file –  codehead Aug 24 '10 at 4:05

Here's a way to do it using GNU grep:

grep -Po "^[^;]+(?=;?)" filename
share|improve this answer
    
Without Gnu grep: grep -Eo '^[^;]+;' filename almost gets it, it just prints one character too many. grep -Eo '^[^;]+' filename almost gets it too, but it will also print complete (non-empty) lines that don't have any ;. –  dubiousjim Apr 19 '12 at 21:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.