0

is it possible to print the field that contain a certain value?

Consider below file:

foo,boo,123,1234312,ABC
foo,boo,ABC,bla,bla

There is a field that contain ABC but it is not a fixed with all records, so the command need to print $5 in the first record and $3 in the second one.

  • 1
    It sounds to me like this could be simplified to grep -q ABC file && echo ABC ? – Jeff Schaller Oct 3 '15 at 13:24
  • What you described is print ABC if record contains ABC. Is this what you want. – ctrl-alt-delor Oct 3 '15 at 14:25
3

Yes, just like in your previous question, but match each field:

$ awk -F, '{for(i=1;i<=NF;i++){if($i~/ABC/){print $i}}}' file
ABC
ABC

Note that the above will also print a filed that contains ABC, like fooABC or fooABCbar or whatever. To print only fields that are ABC, use:

awk -F, '{for(i=1;i<=NF;i++){if($i=="ABC"){print $i}}}' file

The same thing, in Perl:

perl -F, -lane 'print grep{/ABC/}@F' file     ## field matches
perl -F, -lane 'print grep{$_=="ABC"}@F' file ## field is
2

You can use grep with PCRE (Perl Compatible RegEx):

grep -Po '(?<=^|,)ABC(?=,|$)' file.txt
  • 1
    For most cases is enough '\bABC\b' regexp – Costas Oct 3 '15 at 12:59

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.