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.

2
  • 1
    It sounds to me like this could be simplified to grep -q ABC file && echo ABC ? Commented Oct 3, 2015 at 13:24
  • What you described is print ABC if record contains ABC. Is this what you want. Commented Oct 3, 2015 at 14:25

2 Answers 2

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
  • 1
    For most cases is enough '\bABC\b' regexp Commented Oct 3, 2015 at 12:59

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.