4

I have the following file pattern:

insert_buffer cell_a 
insert_buffer cell_b
insert_buffer cell_b
...

I want to add one more column to the end of each line with incremented number. e.x. 0,1,2,3...:

insert_buffer cell_a name_0
insert_buffer cell_b name_1
insert_buffer cell_b name_2
...

How do I for loop using awk? Or any other solution is fine.

1
  • To make it more generic, what if I want to insert the incremental pattern in a specific column? insert_buffer name_0 cell_a insert_buffer name_1 cell_b insert_buffer name_2 cell_b
    – Bryan
    Commented Jun 13, 2017 at 23:52

2 Answers 2

4
$ awk '{$(NF+1) = "name_"(NR-1)} 1' file
insert_buffer cell_a name_0
insert_buffer cell_b name_1
insert_buffer cell_b name_2

If you want to use your own variable in place of the built-in record count NR, then for example

$ awk '{$(NF+1) = "name_"i++} 1' file
insert_buffer cell_a name_0
insert_buffer cell_b name_1
insert_buffer cell_b name_2

If you want to insert the new field elsewhere, then one way to do that is to prepend or append it to an existing field, along with an additional output field separator OFS e.g. to insert before the second field

$ awk '{$2 = "name_"i++ OFS $2 } 1' file
insert_buffer name_0 cell_a
insert_buffer name_1 cell_b
insert_buffer name_2 cell_b
6
  • Thank you this works. Is there a way to incr var i let's say? insert_buffer cell_a -cell_name_${i} -net_name_${i}
    – Bryan
    Commented Jun 13, 2017 at 23:45
  • 1
    @Bryan see edit - is that better? Commented Jun 13, 2017 at 23:48
  • Thank you! How do I make it more generic? Say I wanna insert the 'name_${i}' in any column, not just the last column?
    – Bryan
    Commented Jun 13, 2017 at 23:55
  • Nice hack setting the number of fields to include the new field. I'm not an awk guru; is that "1" at the end a short-cut to print the current line? Commented Jun 13, 2017 at 23:55
  • 1
    The (NR-1) trick left me speachless! Commented Jun 14, 2017 at 0:04
1

This can be done using the sed editor as given:

Note that since sed has no notion of arithmetic, it can be done by other means.

the variable $n stores the column number where you want the new data placed.

n=2;
sed -ne 1i\\ -e 0 -e p\;= yourfile |\
sed -nE "N;s/\S\+/&\n/$n;s/\(.*\)\n\(.*\)\n/\2 name_\1 /p"

Results

insert_buffer name_0  cell_a
insert_buffer name_1  cell_b
insert_buffer name_2  cell_c

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .