Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a number to column [line by line]

I have a text file named text: The row and columns are:

1   A   18  -180
2   B   19  -180
3   C   20  -150
50  D   21  -100
128 E   22  -130
10  F   23  -0
10  G   23  -0

What I want to do is to print out the 4th column with adding a constant number to each of the lines (except ==0). To do this is what I have done.

 #!/bin/bash

FILE="/dir/text"

while IFS= read -r line
do
    echo "$line"
done <"$FILE"

I can read the fourth column, but at the same time I want to put an argument $1 which will add a constant number to all of the lines in the fourth column except any line of the fourth column has ==0.

UPDATE:

The Desired output would be like: [the line has zeros are ignored]

-160
-160
-130
-80
-110

For example, the program name is example.sh. I want to add a number to the fourth column using an argument. Therefore it would be:

example.sh $1

where $1 could be any number I want to add in the 4th column.

like image 953
zero_field Avatar asked Dec 14 '25 03:12

zero_field


1 Answers

You should awk here which will be faster than bash.

awk -v number="100" '$4!=0{$4+=number} 1' Input_file

number is an awk variable where you could set its value as per your need.

Explanation: Adding detailed explanation for above code.

awk -v number="100" '   ##Starting awk program from here and creating a variable number whose value is 100.
$4!=0{                  ##Checking condition if 4th column is NOT zero then do following.
  $4+=number            ##Adding variable number to 4th column here.
}
1                       ##Mentioning 1 will print edited/non-edited lines.
' Input_file            ##mentioning Input_file name here.
like image 143
RavinderSingh13 Avatar answered Dec 16 '25 19:12

RavinderSingh13



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!