2

Content of a sample file is as follow:

AA BB CC DD BB
1  2  3  4  9
5  6  7  8  10

I want to display the whole columns that contain BB and DD. In the real case, I do not know which columns contain the strings BB and DD. And additionally, it will be great to determine order of the columns that will be printed.

The desired output is:

BB DD BB
2  4  9
6  8  10

When it is said that DD column must be first, the desired output is:

DD BB BB
4  2  9
8  6  10

Column ordering may given in a string e.g. cols="BB, DD".

Delimiter of the input file may change.

5

You might run into problems with cut if you have multiple spaces as the delimiter. You could use awk:

$ awk '{print $2, $4, $5}' OFS='\t' inputfile
BB      DD      BB
2       4       9
6       8       10

(You could supply the input and output delimiter using FS and OFS respectively.)


EDIT: As per your comments, if the values are in unknown columns you could say:

awk 'NR==1{for(i=1; i<=NF; i++) if ($i=="BB" || $i=="DD") {a[i]++;} } { for (i in a) printf "%s\t", $i; printf "\n"}' filename

For your input, it'd result in:

BB      DD      BB
2       4       9
6       8       10

It works by keeping a track of the columns in the first row containing BB or DD and then printing out those columns.

If you intend to use a variable for storing the column values, you could declare one like:

pattern="^BB$|^DD$"

(note that the anchors ^ & $ have been added to ensure that BB doesn't match ABB and so on. | is, again, a regex metacharacter denoting or)

and then say:

awk -vp="$pattern" 'NR==1{for(i=1; i<=NF; i++) if ($i~p) {a[i]++;} } { for (i in a) printf "%s\t", $i; printf "\n"}' filename
  • Dear @devnull, I have updated my question. The column indices are not known beforehand. – Kadir Feb 12 '14 at 9:34
  • Dear @devnull, it is a very good solution! Is it possible to get column names from a variable such as cols="BB, DD" or cols="BB DD" and display the columns in the order they appear in the variable? – Kadir Feb 13 '14 at 6:53
  • @Kadir I've added an update. Please attempt to provide all information in the question in one go in the future. – devnull Feb 13 '14 at 7:08
  • Dear @devnull, pattern="^BB$|^DD$" and pattern="^DD$|^BB$" give the same column ordering. Is it possible to display the columns in the order they appear in the variable named pattern. – Kadir Feb 21 '14 at 5:51
  • Dear @Kadir, As I mentioned earlier, do not keep revising your question until eternity. If you are not clear of what you want to ask, don't post a question in the first place. – devnull Feb 23 '14 at 12:01

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.