-1

Using bash, lets say i have the following string

string="Same bought 5 bananas, 12 apples, 2 peaches and 16 oranges"

How can I trim everything except the nth number. In this case I want to output 12 which is the second number in the string.

How can I do that with bash, grep or sed?

Bret Joseph
  • 401
  • 3
  • 13
  • If X is unknown, how do you establish that it's X? – tripleee Dec 12 '18 at 11:32
  • @tripleee im representing the unknown with X.. X is actually an interger – Bret Joseph Dec 12 '18 at 11:34
  • What I am trying to say is that your question is unclear. What would an acceptable answer look like if we don't know what X is, or how we can find out? – tripleee Dec 12 '18 at 11:39
  • Obviously if you know that X is 1, the answer is trivial; `sed 's/.*1.*/1/` but then what do you need the variable for? The result after the substitution is clearly identical to the input string, so there is no point in performing any substitution. Or are you trying to find out if the string contains 1? `case $string in *1*) echo true;; esac` – tripleee Dec 12 '18 at 11:40
  • the problem is I don't want to use the character `1` since X it not always 1 – Bret Joseph Dec 12 '18 at 11:44
  • You still hve not revealed how we, or you, establish the value of X. Are you simply looking for the first numeric string? `grep -Eo '[0-9]+' <<<"$string"| head -n 1` ... But you see, I have already guessed three times and each of these guesses seem plausible, yet produce wildly different results. – tripleee Dec 12 '18 at 11:48
  • X is just a random number that comes with the string, but like you are saying I can probably grep only the first number on the string, thats what I'd like to be outputed – Bret Joseph Dec 12 '18 at 11:54
  • @tripleee please look at the question now and see that it has improved – Bret Joseph Jan 01 '19 at 05:18

2 Answers2

1

Solution Using sed

According to Paul Hodges and Triplee grep -Eo '[0-9]+' <<<"$string"| sed 'nq;d'


Where n is the position of the number

sed 'NUMq;d'
NUM is the lines to print.
2q says quit on the second line.
d will delete every other line except the last

Bret Joseph
  • 401
  • 3
  • 13
  • 3
    `'2q'` says quit on the second line, but won't stop the line from being printed. `'d'` says delete every line you come to, which *does* prevent those lines from being printed. It checks them in order though, so `'2q;d'` will quit (and flush-print) on line 2 before it hits the delete, but not on line one, so the `d` prevents printing of line 1 but not line 2. – Paul Hodges Dec 12 '18 at 15:07
1

This might work for you (GNU sed):

sed 's/^\([^0-9]*\([0-9]*\)\)\{2\}.*/\2/;/^$/d' file

This replaces the current line by the second occurrence of a group of numbers. The line is deleted unless a number is output.

potong
  • 55,640
  • 6
  • 51
  • 83