0

I have a data file with two columns of numbers:

input file

4.182   4.1843
4.184   4.2648
4.2281  4.0819
4.2204  4.1676
4.0482  4.1683
4.0156  4.2895
4.4504  5.2369
4.3776  4.4979
4.3797  4.1372
4.1411  4.0528

I need to insert one column of numbers evenly spaced to the input data file. For example, in the output were inserted a column of numbers spaced by 5. ,so the numbers are 1 , 6, 11,16 , and so on

output

1   4.182   4.1843
6   4.184   4.2648
11  4.2281  4.0819
16  4.2204  4.1676
21  4.0482  4.1683
26  4.0156  4.2895
31  4.4504  5.2369
36  4.3776  4.4979
41  4.3797  4.1372
46  4.1411  4.0528
3
  • I do not understand the question, your in put file hasve 9 row but output have 10 row!!! ,, and whats 1,6,11,.. ? more explain
    – Baba
    Jun 21, 2016 at 19:46
  • Where do the new numbers come from?
    – Law29
    Jun 21, 2016 at 20:00
  • Dear @Babyy, I made a mistake, but now the question are ok
    – alloppp
    Jun 21, 2016 at 20:50

2 Answers 2

1
  1. Create an index-column on the original data file, using pr -t -n.
  2. Create the index data to be inserted as the new column, with each row of index data indexed by the row number. I used a little bash function to do this below.
  3. Join the index column with the data using join.

Here's a bash script to demonstrate:

#!/usr/bin/env bash
# insert-counts.sh

cols='/tmp/cols'
cat <<'EOF' | pr -t -n >$cols
4.184   4.2648
4.2281  4.0819
4.2204  4.1676
4.0482  4.1683
4.0156  4.2895
4.4504  5.2369
4.3776  4.4979
4.3797  4.1372
4.1411  4.0528
EOF

# gen_index START NUM INC
gen_index() {
  local start="$1" num="$2" inc="$3"
  local x
  for ((x = 0; x < num; x++)); do
    printf "%2d  %4d\n" $(( x + 1 )) $(( start + (x * inc) ))
  done
}

lines=`wc -l <$cols`

gen_index 1 $lines 5 |
join -o 1.2 -o 2.2 -o 2.3 - $cols |
awk '{printf("%4d  %8.4f  %8.4f\n",$1,$2,$3);}'

And, here's the output:

$ ./insert_counts.sh
   1    4.1840    4.2648
   6    4.2281    4.0819
  11    4.2204    4.1676
  16    4.0482    4.1683
  21    4.0156    4.2895
  26    4.4504    5.2369
  31    4.3776    4.4979
  36    4.3797    4.1372
  41    4.1411    4.0528
0

If I understand your index generation correctly, then

awk '{print 5*(NR-1)+1" "$0}' yourfile > oufile

should do it. If you want prettier output, you can use printf instead e.g.

$ awk '{printf "%-3d %s\n", 5*(NR-1)+1, $0}' yourfile
1   4.184   4.2648
6   4.2281  4.0819
11  4.2204  4.1676
16  4.0482  4.1683
21  4.0156  4.2895
26  4.4504  5.2369
31  4.3776  4.4979
36  4.3797  4.1372
41  4.1411  4.0528

You must log in to answer this question.

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