3

I'm currently writing a shell script that separate 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

3 Answers 3

3

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 " " -
4
  • Thanks, is there some way I can get it to print without the newlines though?
    – sj755
    Feb 16, 2013 at 1:00
  • 1
    See my edited post Feb 16, 2013 at 1:01
  • 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, 2013 at 1:07
  • 1
    @terdon Well aware, I'm waiting to be allowed to check off the answer.
    – sj755
    Feb 16, 2013 at 1:10
3

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

… | sed 's/^[^=]*= *//' | tr '\n' ' '; echo
1

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .