kpw
kpw

Reputation: 45

Substitute a value only when greater than

Trying to substitute a value in a number of files using shell commands (to use in a script to iterate over the files in a directory).

Input file examples:

file1:
019=False
051=Limited
051>Limited Lease Time=2419200

file2:
019=False
051=Limited
051>Limited Lease Time=14400

This worked okay:

sed -e '/Limited Lease Time=/s/[0-9]\+$/86400/g' <infile >outfile

# cat outfile
019=False
051=Limited
051>Limited Lease Time=86400

But ... then realised that I was replacing any value, including ones lower than 86400, when I only want to replace anything greater than 86400.

I thought I could use awk, and this 'kind of' worked, as in the output was only 'Limited Lease Time' lines that has a value > 86400:

awk -F= '/Limited Lease Time/ && $2 > 86400 { print $2 }'

But ... it's only outputing the matched line, whereas I need the original output (3 lines in the examples), including the modification, if the matched value > 86400.

Appreciate some advice on a way to handle this !

Upvotes: 2

Views: 195

Answers (1)

Inian
Inian

Reputation: 85845

Use the = field-separator in Awk and get lines in $2 greater than the value you have set,

awk 'BEGIN{FS=OFS="="} $0 ~ /\<Limited Lease Time\>/ && $2 > 86400 {$2=86400}1' file

For an input-file,

cat file
019=False
051=Limited
051>Limited Lease Time=14400
051>Limited Lease Time=94400
051>Limited Time=14400

Running the command produces output as you needed.

awk 'BEGIN{FS=OFS="="} $0 ~ /\<Limited Lease Time\>/ && $2 > 86400 {$2=86400}1' file
019=False
051=Limited
051>Limited Lease Time=14400
051>Limited Lease Time=86400
051>Limited Time=14400

Also you can make it configurable by using the -v variable import in Awk

awk -v thresh=86400 'BEGIN{FS=OFS="="} $0 ~ /\<Limited Lease Time\>/ && $2 > thresh {$2=thresh}1' file

Upvotes: 5

Related Questions