![Anhängen einer Spalte an eine Datei basierend auf der Zeilennummer](https://rvso.com/image/168800/Anh%C3%A4ngen%20einer%20Spalte%20an%20eine%20Datei%20basierend%20auf%20der%20Zeilennummer.png)
Ich habe eine Liste von Zahlen, die ich am Ende einer anderen Datei als letzte Spalte hinzufügen möchte:
1:.196
5:.964
6:.172
Die Zahlen davor (1,5 und 6) geben an, an welcher Zeile in der Zieldatei die Zahlen angehängt werden müssen, damit die erste Zeile mit endet .196
, die fünfte mit .964
und so weiter. Üblicherweise paste file1 file2
wird auf die Zeilennummern nicht geachtet und einfach 1:.196
am Ende der ersten Zeile und .964
am Ende der zweiten statt der fünften angehängt. Irgendwelche Ideen, wie man das richtig macht?
Erwartet würde etwa Folgendes:
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
Antwort1
Mit 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
Ausgabe:
one.196
two
three
four
five.964
six.172
Erläuterung:
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
Antwort2
$ sed 's/:/s:$:/;s/$/:/' nums_file |
sed -f - file
Erläuterung:
° 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.