I'm trying to write a script that increments an integer found in a config file. I'm trying to use grep
to find the current value:
$ grep versionNumber myfile.conf
versionNumber 123789
^ whitespace
^ the key I need to match
^ the value I need to capture
My desired result is to capture the 123789
in the example above.
What do I need to do in order to capture this value?
You can do this:
grep versionNumber myfile.conf | grep -oE '[0-9]+'
or this
grep versionNumber myfile.conf | awk '{print $2}'
or this
grep versionNumber myfile.conf | cut -d' ' -f2
or if you have GNU grep with support for the -P
mode:
grep -oP 'versionNumber \K\d+' myfile.conf
使用awk
awk '/versionNumber/{print $2}' myfile.conf
Using grep -oP
(pcre mode);
s=' versionNumber 123789'
grep -oP 'versionNumber\h+\K\S+' <<< "$s"
123789
script that increments an integer found in a config file using Gnu awk v. 4.1.0+:
A test file:
$ cat > file
foo
versionNumber 123789
bar
Using inplace edit feature:
$ awk -i inplace '/versionNumber/ {n=index($0,"v"); sub($2,$2+1); printf "%-"n"s\n", $0; next} 1' file
The result:
$ cat file
foo
versionNumber 123790
bar
Explanation:
Key to editing the file inplace is -i inplace
/versionNumber/ { # if versionNumber found in record
n=index($0,"v") # count leading space amount to n
sub($2,$2+1) # increment the number in second field
printf "%-"n"s\n", $0 # print n space before the (trimmed) record
next # skip print in the next line
} 1 # print all other records as were
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.