0

How can I read the value "5" in the following example to issue 5 copies of file print?

For example.. My output is similar to the code below.


Order: 101
Guest: Raj
Phone: xxx-xxx-xxxx

5 x Bananas
5 x Grapes
5 x Apples

how can I read value 5 in the above file and use is as below. If there is a way to get 5 in a variable, I can use it in the lpr command.

lpr output.txt -#

mu is too short
  • 426,620
  • 70
  • 833
  • 800
VKA
  • 209
  • 1
  • 7
  • 16

2 Answers2

0

I would do something like this:

sed -n '/^[0-9]\+ x [A-Za-z]\+/ { s/^\([0-9]\+\) x \([A-Za-z]\+\)/\1 \2/; p }' file |
while read num fruit; do
  echo $num $fruit
  # do whatever with lpr
done

Edit

If all you want to do is find the unique ## where you have a string like ## x Something, you can use this:

sed -n '/^[0-9]\+ x [A-Za-z]\+/ { s/^\([0-9]\+\) x.*/\1/; p }' file | uniq

If you want to capture that to a variable, use:

var="$(sed -n '/^[0-9]\+ x [A-Za-z]\+/ { s/^\([0-9]\+\) x.*/\1/; p }' file | uniq)"
Tim Pote
  • 27,191
  • 6
  • 63
  • 65
  • It works great..however, it is printing 5 multiple times. how can I print it only once? – VKA Apr 27 '12 at 03:37
  • @RajK I'm confused as to what you want. Do you want it to just find the first `5` in the file and print that? If that's the case why don't you just use the number 5? I assumed that what you wanted was to find all of the lines that look like '## x Something' and print out the number it found. If that's not what you want, can you clarify your question? – Tim Pote Apr 27 '12 at 03:43
  • sorry for the confusion. The output I listed is generated from other program and stored in a file. Now from the file, I want to read the number before "x" sign like 5 in above example and store it in a variable with in my shell script to use with lpr. Does this make sense...? – VKA Apr 27 '12 at 03:48
  • Yeah that makes sense. That's exactly what my answer does. The reason you get multiple `5`s is because there are multiple instances of `5 x` in the file. – Tim Pote Apr 27 '12 at 03:59
  • So is there a way to trim more than 1 value.. I tried storing this output in a variable and printing it.. does not work... – VKA Apr 27 '12 at 14:03
0

This will be helpful.

egrep '[0-9]+' test | cut -f 1 -d " " | uniq 
ganesshkumar
  • 1,317
  • 1
  • 16
  • 35
  • This assumes that the sample input will always be at the bottom of a file. You'd probably be better off using `egrep '[0-9]+'` instead of tail. As is, this is also an example of a [Useless Use of Cat](http://partmaps.org/era/unix/award.html#cat). You can just call `cut -f 1 -d " " filename` instead. – Tim Pote Apr 27 '12 at 11:54