![Добавить столбец в файл на основе номера строки](https://rvso.com/image/168800/%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D1%81%D1%82%D0%BE%D0%BB%D0%B1%D0%B5%D1%86%20%D0%B2%20%D1%84%D0%B0%D0%B9%D0%BB%20%D0%BD%D0%B0%20%D0%BE%D1%81%D0%BD%D0%BE%D0%B2%D0%B5%20%D0%BD%D0%BE%D0%BC%D0%B5%D1%80%D0%B0%20%D1%81%D1%82%D1%80%D0%BE%D0%BA%D0%B8.png)
У меня есть список чисел, которые я хотел бы добавить в конец другого файла в качестве последнего столбца:
1:.196
5:.964
6:.172
Цифры впереди (1,5 и 6) указывают, в какую строку нужно добавить цифры в целевом файле, так что первая строка заканчивается на .196
, пятая на .964
и т. д. Обычно paste file1 file2
не учитываются номера строк, а просто добавляются 1:.196
в конце первой строки и .964
в конце второй вместо пятой. Есть идеи, как это сделать правильно?
Ожидается что-то вроде этого:
Lorem Ipsum 1238 Dolor Sit 4559.196
Lorem Ipsum 4589 Sit elitr 1234
Lorem Ipsum 3215 Dolor Sit 5678
Lorem Ipsum 7825 Dolor Sit 9101
Lorem Ipsum 1865 Dolor Sit 1234.964
решение1
С awk
:
# create two test files
printf '%s\n' one two three four five six > target_file
printf '%s\n' 1:.196 5:.964 6:.172 > numbers
awk -F':' 'NR==FNR{ a[$1]=$2; next } FNR in a{ $0=$0 a[FNR] }1' numbers target_file
Выход:
one.196
two
three
four
five.964
six.172
Объяснение:
awk -F':' ' # use `:` as input field separator
NR==FNR { # if this is the first file, then...
a[$1]=$2 # save the second field in array `a` using the first field as index
next # stop processing, continue with the next line
}
FNR in a { # test if the current line number is present in the array
$0=$0 a[FNR] # append array value to the current line
}
1 # print the current line
' numbers target_file
решение2
$ sed 's/:/s:$:/;s/$/:/' nums_file |
sed -f - file
Объяснение:
° use the number file to create the sed commands to operate on the actual data
° Pass these sed commands over the pipe and use sed to apply them on the data file.