tags:

views:

36

answers:

1

000 000 000 000 (4 fields each of which is a group of 3 zeros separated by a space)

Process to generate 4 new lines

100 000 000 000

000 100 000 000

000 000 100 000

000 000 000 100

On ea line a group of three zeros is replaced by 100

How can I do this ?

tom

+1  A: 
$ echo '000 000 000 000' | awk '{for (i=1;i<=NF;i++) {f=$i; $i="100"; print; $i=f}}'
100 000 000 000
000 100 000 000
000 000 100 000
000 000 000 100

Edit:

The fields are iterated over using the for loop. Each field ($i - for the field number i) is saved to a temporary variable f. Then the contents of the field are replaced. The record ($0) is printed. The field is returned to its previous value using the temporary value.

It might be easier to follow if this data was used: 001 002 003 004. Then the output would look like:

100 002 003 004
001 100 003 004
001 002 100 004
001 002 003 100

Here's a shell script version using sed:

data='001 002 003 004'    # or 000 000 000 000
for i in {1..4}; do echo "$data" | sed "s/\<[0-9]\{3\}\>/100/$i"; done

or

count=$(echo "data" | $wc -w)
for ((i=1;i<=count;i++)); do echo "$data" | sed "s/\<[0-9]\{3\}\>/100/$i"; done

or Bash without any external utilities:

data=(001 002 003 004)    # use an array
count=${#data[@]}
for ((i=0;i<count;i++)); do f=${data[i]}; data[i]=100; echo "${data[@]}"; data[i]=$f; done

Or many other possibilities.

Dennis Williamson
Nice one! how does it work ?
Tom
@Tom: see my edit.
Dennis Williamson
i geddit: appreciated
Tom
As an unreformable noob, I like the awk thing coz it seems to travel in a nice straight line. It simply accents what awk 'likes to do' wh is print out fields by their number: awk expressions are so often lumpy and hard to get. This one isn't like that.
Tom
@Tom: I'm really curious what this is for.
Dennis Williamson
@Dennis: It's for a spreadsheet filter. I've got too many columns. I need to sift them. The actual input string is about 80 digits long. Thanks again.
Tom