Score:3

Is there any way I can search in a file for Uptime that is greater than 100 days?

kr flag

Is there any way I can search in a file for Uptime that is greater than 100 days via Linux Bash commands?

For example, file1 contains:

Uptime is 172 days

Uptime is 562 days

Uptime is 30 days

downtime is 197 days

What command can I use to get an output like:

Uptime is 172 days

Uptime is 562 days
user535733 avatar
cn flag
This seems like a homework question.
Score:6
cn flag

Here is a simple awk solution:

awk '$1 == "Uptime" && $3 > 100 {print}' file1
Uptime is 172 days
Uptime is 562 days
Raffa avatar
jp flag
Might be simpler as well `awk '/Uptime/ && $3 > 100' file1`
Score:5
cn flag

...and a bit more complex bash solution:

while read -r a b c d; do
   [[ $a = Uptime && $c -gt 100 ]] && printf '%s %s %s %s\n' $a $b $c $d
done < uptime
Uptime is 172 days
Uptime is 562 days
Score:4
it flag

And a grep solution, using Extended Regexps:

grep -E 'Uptime is [[:digit:]]{3}' uptime | \
  grep -Ev 'Uptime is 100'

This will find the "Uptime is " string, followed by at least 3 digits, and discard the exact 100 followed by End-of-line.

David Foerster avatar
us flag
Better use `[[:digit:]]{3,}` (note the comma) for numbers with more than 3 digits. If leading zeros are possible, one can use `0*[1-9][0-9]{2,}` to not include those into the count.
marcelm avatar
cn flag
@DavidFoerster The expression in the answer will work, because it's not anchored in any way to the end. For a line with, say, four digits, the expression will only match the first three digits, but since the expression terminates there, that will match the line. But I agree your expression is better style; it better expresses intent, and is more likely to continue working if the expression is modified.
vn flag
Wouldn't this also match uptimes of 100 days, whereas the question asks for uptimes of more than 100?
Score:2
id flag

Converting from my comment.

Using grep and awk together:

grep "Uptime" file1 | awk '$3 > 100 {print}'

Look for "Uptime" in file1 and then look at the 3rd column and print if greater than 100.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.