How can I adjust nth number in a line?
Using awk
:
awk '{ for (i=1;i<=NF;i++) { if ($i ~ /num2=/) {sub(/num2=/, "", $i); $i="num2="$i-5; print} } }' file
This will loop through each column of each line looking for the column that contains num2=
. When it finds that column it will:
- Remove
num2=
-sub(/num2=/, "", $i)
- Redefine that column as
num2={oldnum-5}
-$i="num2="$i-5
- Print the line -
print
perl:
perl -pe 's/(?<=num2=)(\d+)/$1 - 5/e' file
To store the contents back into the file:
perl -i -pe ...
[Just because I'm trying to become more familiar with Miller - it requires some jumping through hoops to get the heterogeneous output]:
$ mlr --fs ' ' --repifs --ocsvlite --headerless-csv-output put '
$num1 = "num1=".$num1; $num2 = "num2=".($num2-5)
' file
RANDOM TEXT num1=400 num2=10 RANDOM TEXT
RANDOM TEXT num1=300 num2=5 RANDOM TEXT
RANDOM TEXT num1=200 num2=0 RANDOM TEXT
If the input is actually TSV in which some columns may contain spaces, then
$ mlr --fs '\t' --ocsvlite --headerless-csv-output put '
$num1 = "num1=".$num1; $num2 = "num2=".($num2-5)
' file
RANDOM TEXT num1=400 num2=10 RANDOM TEXT
RANDOM TEXT num1=300 num2=5 RANDOM TEXT
RANDOM TEXT num1=200 num2=0 RANDOM TEXT