People who code: we want your input. Take the Survey

Hot answers tagged

5

To start with, here's how to capture the numeric value: $ echo 'foo = 1700;' | sed -n -e 's/^foo = \([0-9]\+\).*/\1/p' 1700 That's using sed's default Basic Regular Expressions (BRE). You can also use Extended Regular Expressions (ERE) with sed's -E option: echo 'foo = 1700;' | sed -n -E -e 's/^foo = ([0-9]+).*/\1/p' 1700 The sub-expression [0-9]+ inside ...


1

Assuming you want to pick out a numeric foo value, echo 'foo = 1700;' | awk '$1=="foo" {print $NF+0}' 1700 By default awk splits on whitespace (not just a single space). NF is the number of fields, in this case 3; $NF is the string value of the 3rd whitespaced field. The +0 converts this string 1700; to the numeric value 1700. It will work on ...


1

For completeness, with grep implementations that support -o and perl-like regular expressions with -P, you can do: grep -Po 'foo\s*=\s*\K\d+' Where: \s matches any whitespace character * 0 or more of the preceding atom. So \s* for instance matches 0 or more whitespace characters. \d matches a decimal digit (generally the same as [0123456789], though not [0-...


1

Using gawk: Assuming file input as: $ cat input foo = 1700 foo=17 foo 2000 foobar = 200 foo = foo = 14 243 foo = 200 = foo This gawk command would do: awk '{if(match($0, /foo\s*=\s*[0-9]+/)){ a=substr($0,RSTART,RLENGTH);sub(/foo\s*=\s*/, "",a); print a}}' input Or with this awk command: awk '{if(match($0, /foo[[:space:]]*=[[:space:]]*[...


1

For all of you regex lovers seeking the perfect match, one that does take into account the <>'s inside quotes would be: sed -E 's/<([^">]|"[^"]*")*>//g' Which means: "REPLACE a < followed by any number of ((not a > or a ") OR (a ", but then it must be followed by any number of (not a ") and then a ...


1

Substitution expressions in sed support a numeric flag. Here's how GNU sed can do it: sed 's/:/-/g;s/-/:/3g' So what's going on here? This expression has two parts, separated by ;. Here they are: First, replace all colons with hypens Then replace all hyphens except the first 2 with colons This isn't generally useful in cases where your initial string has ...


Only top voted, non community-wiki answers of a minimum length are eligible