如何將一列數字新增至數組資料文件

如何將一列數字新增至數組資料文件

我有一個包含兩列數字的資料檔:

輸入檔

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

我需要將一列均勻間隔的數字插入輸入資料檔中。例如,在輸出中插入了一列間隔為 5 的數字,因此數字為 1 、 6、 11,16 等

輸出

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

答案1

  1. 使用 . 在原始資料檔案上建立索引列pr -t -n
  2. 建立要作為新列插入的索引數據,每行索引資料都按行號索引。下面我使用了一個 bash 函數來完成此操作。
  3. 加入索引列數據使用join

這是一個用於演示的 bash 腳本:

#!/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);}'

並且,這是輸出:

$ ./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

答案2

如果我正確理解你的索引生成,那麼

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

應該這樣做。如果你想要更漂亮的輸出,你可以使用printf例如

$ 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

相關內容