Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I know how to redirect first 5 lines of the output to a file when I execute a command. I want to know how to redirect only specific information from the output.

For example I would like to execute the command "free -m" and redirect the column "used" from the output to a text file.

How to do this without editing the whole output manually?

share|improve this question
    
So, your question is about lines or about columns? –  lcd047 Jun 8 at 5:02
    
My question is about extracting from the output only the things that i need.. In that case with "free -m" is to redirect only the column "used". –  Xleboniarhs Jon Jun 8 at 11:09

1 Answer 1

up vote 2 down vote accepted

I'm sure there are more elegant answers but this should work:

free -m | awk '{if (NR == 1) {print $2} else {print $3}}' > file.out

This command takes the standard output from free -m and sends it to awk. For the first line, it prints the second column (here, the title of the column of interest), otherwise it prints the third column (the subsequent lines in free -m have an extra column).

share|improve this answer
    
Nice, it works. So in general in order to manipulate the output of a command i have to use awk right? If i go learn more about awk will it allow me to extract only a specific line and column? E.g The first two lines in the second column. –  Xleboniarhs Jon Jun 8 at 11:21
    
It depends a little on the output. I use awk, used, grep, or a python or perl script. If you are looking for something simple like the third column awk works well. There are of course other ways to do it. I think learning a little awk will be very helpful for these types of extractions. –  user1794469 Jun 8 at 12:59
    
Ok thanks that was helpful. –  Xleboniarhs Jon Jun 8 at 13:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.