9

How can I use awk to remove all text after a certain character ";" that appears on every line of my text file? (I then need to run for loops on the text)

Jenny,Sarah,John;North Dakota

Henry,Frank;Illinois

Aaron,Kathryn,Caitlin,Harris;New York
  • 1
    Please show us the actual text file, the devil's in the details with this kind of thing. – terdon Feb 28 '14 at 3:54
  • I gave an example now @terdon – Jenny Feb 28 '14 at 3:59
16

There are two general approaches.

  1. Set awk's field separator to that character. You can then get the parts you want as $1:

    $ echo "Today was cloudy; yesterday too" | awk -F';' '{print $1}'
    Today was cloudy
    
  2. Use gsub() to substitute it with an empty string:

    $ echo "Today was cloudy; yesterday too" | awk '{sub(/;.*/,""); print}'
    Today was cloudy
    

So, for your example:

$ awk -F';' '{print $1}' file
Jenny,Sarah,John

Henry,Frank

Aaron,Kathryn,Caitlin,Harris
4

Here's an answer with sed -- since you're not really doing any field processing, awk is probably overkill.

sed 's/;.*//'
  • 1
    +1 but based on the OP's comments, I am assuming this is all part of a larger script. @Jenny, that's the kind of detail you should include in your questions by the way. – terdon Feb 28 '14 at 4:13
4

And also just cut ..

cut -d\; -f1 file
0

Sometimes you may want to replace all characters after a certain word with another string. For example:

original_string="abc blabla foo bar" and you want to replace words after blabla with 'hello world'

echo $original_string | sed -E 's/(.+ blabla) .+/\1 hello world/'

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.