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.

up vote 5 down vote accepted

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

sed 's/^\([^;][^;]*\);.*$/\1/' some_file_name
  • 6
    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
  • 8
    useless us of cat – user601 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

  • 7
    useless use of cat. – Dennis Williamson Aug 24 '10 at 1:18
  • 1
    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
  • 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

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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