13

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.

4 Answers 4

9

another option is to use the cut command

cat a.file | cut -d';' -f1
1
  • 9
    useless us of cat
    – user601
    Aug 23, 2010 at 18:35
5

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

sed 's/^\([^;][^;]*\);.*$/\1/' some_file_name
3
  • 7
    This is more complicated than it should be! sed 's/;.*//' Aug 23, 2010 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, 2010 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, 2012 at 21:06
3

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

2
  • 7
    useless use of cat. Aug 24, 2010 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, 2010 at 4:05
2

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

grep -Po "^[^;]+(?=;?)" filename
1
  • 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, 2012 at 21:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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