I have a variable Test as below

Test="Environment Dev"

I want to compare col2 char 1 with others and print the whole name of env

this is what i did

echo $Test|awk '{
if ($2 == "^D*")
print "DEV";
print "$2"

I am getting $2 as output but if its Test , comparing D with T I want output as TEST

I also tried this but output is not changing when col2 changes.

echo $Test|awk '{
if ($2 ~ "^D*")
print "$2"

Please help where I am making mistake


Some errors I see in your awk script:

  • Use ~ /whatever/ for regular expressions.
  • Do not add an asterisk in the ^D regexp, that will also match zero D characters.
  • Remove the quotes around the $2 to avoid printing it literally.

A possible solution:

echo $Test | awk '{
if ($2 ~ /^D/)
  print "DEV";
  print $2
  • awesome looks like this works. – Maddy Mar 29 '16 at 16:57
  • Roaima - I am not sure how to mark this post as ANSWERED – Maddy Mar 30 '16 at 19:37

If you're using bash or ksh or zsh, you don't even need to use awk, you can use ${parameter#word} to remove a prefix...in this case the prefix of "all characters up to the first space":

$ Test="Environment Dev"
$ SecondWord=${Test#* }
$ echo $SecondWord

$ [[ $SecondWord =~ ^D ]] && echo DEV || echo $SecondWord

$ SecondWord=Foo
$ [[ $SecondWord =~ ^D ]] && echo DEV || echo $SecondWord 

This may work in some other Bourne-like shells, but I tested it only in the three I mentioned above.

BTW, if you want a "greedy" match (i.e. longest matching string rather than shortest - so that you're getting the LAST word rather than the second and subsequent, if any, words), use ## rather than #.

  • Thanks the issue is resolved. THanks all for the answers – Maddy Mar 30 '16 at 19:36

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.