简体   繁体   中英

Linux: comma-delimited text: read last two, add them, place them at end of each line

I have a file that looks like this:

GOES-15,167,170,+,3
GOES-14,150,146,-,4
GOES-13,100,100,-,0
GOES-WEST,-160,-170,-,10

I would like to read the last two elements of each line (for example + and 3 on first line) and add them together side by side (+3) and put it at the end of the line with a comma delimit, so like this:

GOES-15,167,170,+,3, +3

Here is what I am trying:

#!/bin/bash

file=weather_sats.txt

while read line
do
    ADD=$(awk -F, '{print $4$5}')
    sed -i 's/$/,$ADD/' $file
done < $file

exit 0

This doesn't work, since I get,"$ADD" at end of each line. Any help much appreciated!

This might do what you wanted.

awk -F, '{print $0","$(NF-1)$NF}' file.txt

Use pure awk :

awk -F, 'BEGIN { OFS="," } {print $0, $4$5 }'

That produces the required output.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM