tags:

views:

28

answers:

1

I want to add one to the last value at the end of a string in sed. I'm thinking along the lines of

cat 0809_data.csv |sed -e 's/\([0-9]\{6\}\).*\(,[^,]*$\)/\1\2/g'| export YEARS = $(echo `grep -o '[^,]*$' + 1`|bc)

e.g. 123456, kjhsflk, lksjgrlks, 2.8 -> 123456, 3.8

Would this be more reasonable/feasible in awk?

+2  A: 

This should work:

years=$(awk -F, 'BEGIN{ OFS=", "} {print $1, $4+1}' 0809_data.csv)

It would be really awkward to try to use sed and do arithmetic with part of the result. You'd have to pull the string apart and do the math and put everything back together. AWK does that neatly without any fuss.

Notice that cat is not necessary (even using sed in a command similar to the one in your question) and it's probably not necessary to export the variable unless you're calling another script and need it to be able to access it as a "global" variable. Also, shells generally do integer math so you don't need to use bc unless you need floats.

Dennis Williamson
This looks great. Thank you.cat only_0809__data.csv |sed -e 's/\([0-9]\{6\}\).*\(,[^,]*$\)/\1\2/g' |awk 'BEGIN {FS=","}{OFS=", "}{print $1,$2+1}
Donnied
@Donnied: `OFS` should be inside the first set of curly braces (the ones that belong to `BEGIN`) so it only gets executed once instead of on each line. It's not necessary to use `cat`. You can do the regex stuff in the same call to AWK, using `gsub` perhaps, instead of using `sed`.
Dennis Williamson