Take the 2-minute tour ×
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'm currently writing a shell script that seperate values from their identifiers (retrieved from grep).

For example, if I grep a certain file I will retrieve the following information:

value1 = 1
value2 = 74
value3 = 27

I'm wondering what UNIX command I can use to take in the information and convert it to this format:

1 74 27

Appreciate any help

share|improve this question
add comment

3 Answers 3

up vote 3 down vote accepted

You can use like this :

grep "pattern" file.txt | awk '{printf "%s ", $3}'

Depending of what you do with grep, but you should consider using awk for greping itself :

awk '/pattern/{printf "%s ", $3}' file.txt

Another way by taking advantage of word-spliting :

echo $(awk '/pattern/{print $3}' file.txt)

Edit : I have a more funny way to join values :

awk '/pattern/{print $3}' file.txt | paste -sd " " -
share|improve this answer
    
Thanks, is there some way I can get it to print without the newlines though? –  sj755 Feb 16 '13 at 1:00
1  
See my edited post –  sputnick Feb 16 '13 at 1:01
    
Thanks for the help –  sj755 Feb 16 '13 at 1:06
2  
@sj755 If this answer solved your problem, please remember to mark it as accepted and upvote it instead of posting a thank you comment. That is the way thanks are expressed on SE sites. –  terdon Feb 16 '13 at 1:07
1  
@terdon Well aware, I'm waiting to be allowed to check off the answer. –  sj755 Feb 16 '13 at 1:10
add comment

Strip everything up to the first = and subsequent whitespace, convert newlines into spaces, and print a final newline:

… | sed 's/^[^=]*= *//' | tr '\n' ' '; echo
share|improve this answer
add comment

How about simply

cut -d= -f2 /tmp/file | xargs printf "%s "

This works because:

  1. The shell builtin "printf" will will "repeat itself" if it gets more arguments than the parameters specified in the output string
  2. xargs will turn the lines from the input into words on the command line passed to printf
  3. cut will use the = as a separator and deliver only what follows it
  4. Of course the printf string will display the output and since no explicit new line is added, append each to the end of the previous one.
share|improve this answer
add comment

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.