0

I have a file which have contents like this.

Column1     Column2                           Column3             Column4
USER1        25 Years                          xyz zyz               123 abc
USER2        15 Years 2 months blah            abc sdsz sd        123 abc

and so on ...

Now what I want is to print all contents of COLUMN2 and as you can see it have dynamic contents , text can be one word or multiple words with spaces. so i need a way to print column2 contents.

2
  • How do you define the end of column 2? Does it have a fixed width? Sep 8 '15 at 20:49
  • 2nd column does not have fixed width, example the output can be like this is 2nd column text example OR this is 2nd column OR this is 2nd text OR 2nd so how can i print out all text in second column only? Sep 9 '15 at 8:45
0

Use awk:

awk 'NR==1{b=index($0,$2); e=index($0,$3)} {print substr($0,b,e-b)}' file

If the age fields length is dynamic, you first have to find out where it begins and where it ends. The b variable defines the character where the field begins and the e varibale the end. substr() then cuts the string in the desired length.

6
  • but like i said i want to print column2 and it have variable length so cutting specific range may not be suitable,example username can be long, age can be shorter or longer so i want a way to print AGE column fully Sep 8 '15 at 5:50
  • @SyedJahanzaib See my updated answer
    – chaos
    Sep 8 '15 at 5:54
  • No bro its not working. Sep 8 '15 at 6:09
  • @SyedJahanzaib can you then give my a bit more info? Error mesaage? awk version? For me it's working with mawk version 1.3.3 and gawk version 3.1.8 and your demo file.
    – chaos
    Sep 8 '15 at 6:19
  • I have edited the question to provide more clarity. Demo file have contents like this. Column1 Column2 Column3 Column4 USER1 25 Years xyz zyz 123 abc USER2 15 Years 2 months blah abc sdsz sd 123 abc Now what I want to print all contents of COLUMN2 and as you can see it have dynamic contents , text can be one word or multiple words with spaces. so i need a way to print column2 contents. Sep 8 '15 at 8:29

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.