0

Here is my sample input file.

ip.txt:

john    math
        science
paul    math
        science
rosy    math
jill    science
rob     math
        science
hary    math

Desired output:

john

paul

rosy
jill
rob

hary

When I use:

awk '{print $1}' ip.txt

My output is:

john
science
paul
science
rosy
jill
rob
science
hary

I don not want the second column values printed, I want the blank spaces to be printed out to a file.

How can I achieve this? I am using Solaris 5.10 with ksh.

0
4

awk:

awk '{print (NF>1) ? $1 : ""}' file

If the number of fields is more than 1, print the first field, otherwise print an empty line.

A couple of extra thoughts:

  • If your data is tab-separated, then

    awk -F '\t' '{print $1}' file
    
  • If you want to extract the first 8 characters

    awk '{print substr($0,1,8)}' file
    
1

With POSIX sed:

sed -e 's/^\([^[:blank:]]*\)[[:blank:]].*/\1/;t' -ed <file
1

If you want all the extra spaces before the subject field, you can do:

grep -o "^[^ ]* \+" ip.txt

If you don't want the extra spaces:

sed 's/ \+.*//' ip.txt

Both of these will preserve lines with empty name fields.

1
  • 1
    +. The sed one is actually smarter as it preserves even empty lines but probably the fastest solution would be cut -d' ' -f1 ip.txt (assuming spaces). – don_crissti Jul 16 '15 at 18:44

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.