2

Example: Lets say this is in a file:

AB: Test CD: Testing EF: Rest

I want a script to search for CD and save "Testing" into a variable. I've tried something with awk but somehow I'm not making any progress.

2

Using grep and perl style regex you can use positive lookbehind:

variable_a=`grep -Po '(?<=CD: )[^ ]+' file.txt`

In bash this says:

  • Create a variable called variable_a and give it the value of whatever comes out of the command in backticks
  • grep should use perl regex (-P) and only return the matching part of the line (-o)
  • The pattern should match 'CD: ' and then 1 or more characters that are not a space ([^ ])
  • Search 'file.txt' for the pattern
|improve this answer|||||
  • You should mention that's GNU grep only for -P. – Ed Morton Feb 12 at 20:58
  • Thanks alot. Thats pretty good but theres 1 thing im trying to figure out atm. With that way i can print out Testing but the rest too. I need the script to only print out "Testing" – Andehake Feb 13 at 7:51
  • You mean only prints it if it says "Testing"? because it only print Testing now not the rest of the line, but if it said "Alligator" after the CD it would print "Alligator" – user1794469 Feb 13 at 14:46
1

Assuming the sample input/output you posted covers all of your possible use cases then...

With any sed:

$ var=$(sed -n 's/.*CD: \([^ ]*\).*/\1/p' file)
$ echo "$var"
Testing

With any awk:

$ var=$(awk 'sub(/.*CD: /,""){sub(/ .*/,""); print}' file)
$ echo "$var"
Testing
|improve this answer|||||
  • Thanks alot. Thats pretty good but theres 1 thing im trying to figure out atm. With that way i can print out Testing but the rest too. I need the script to only print out "Testing" – Andehake Feb 13 at 7:50
  • As you can see in my answer, the script DOES only print out Testing given the sample input you provided so idk what you comment is about. – Ed Morton Feb 13 at 8:39
  • Sorry you are right. I meant this for example: AB: Test, CD: Testing Word Two, EF: Rest, ... and print out "Testing Word Two" – Andehake Feb 13 at 20:15

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.