tags:

views:

33

answers:

3

Dear all, I read about sed last week and now, I do some extraction from a file using sed, that is fine, Now, I would like to change the data in the first column to the line number say

1 3 3 0 0 0 1 3 35 34
16 3 3 0 0 0 34 35 33 19
31 3 3 0 0 0 19 33 71 68
46 3 3 0 0 0 68 71 72 69
61 3 3 0 0 0 69 72 73 70
76 3 3 0 0 0 70 73 67 53

and change the first column to 1 to 6, how can I do this in awk or sed? Best, Umut

A: 

You can try something like this
echo "1 3 3 0 0 0 1 3 35 34 " | sed 's/^1 /A /g'

Change A to the Number you need and i assume the first column is in the beginning of the line

Raghuram
Say if I would like to do this in a loop where I loop over the lines and indeed update the first column in this fashion, where it is the beginning of the line. I guess awk is a better option because there are some constructs in the language. I am not sure though...
Umut Tabak
and the first column is not always starting with 1.
ghostdog74
+2  A: 

use awk

awk '$1=NR' file
ghostdog74
Thanks, this is the trick, continue on reading the manual...
Umut Tabak
@Umut: If this answer solved your problem, consider accepting it by clicking the checkbox next to it.(+1 Awk is the right tool for this job.)
schot
A: 

Definitely awk for this scenario. The easiest way I could accomplish this with sed was in the following form.

cat file | sed "s/^[0-9]*//g;=;" | sed -n "N;s/\n//g;p"

Where the first expression deletes the first number, and prints the line number = from the read pipe.

The second sed expression retrieves two lines at a time and removes the newline \n.

This could have not been done through two consecutive expressions because the = command directly writes the line number to the standard output, which cannot be captured. So I had to recur to another sed call.

mhitza