2

I have a list of numbers which i would like to add to the end of another file as the final column:

1:.196
5:.964
6:.172

The numbers in front (1,5 and 6) indicate at which line the numbers have to be appended in the target file, so that the first line ends with .196, the fifth with .964 and so on. The usual paste file1 file2 does not take the line numbers into account and simply adds 1:.196 at the end of the first line and .964 at the end of the second instead of the fifth. Any ideas how to do it the right way?

Expected would be something like this:

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

2 Answers 2

4

With 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

Output:

one.196
two
three
four
five.964
six.172

Explanation:

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
1
  • 1
    FNR in a{ $0=$0 a[FNR] }1 can just be {print $0 a[FNR]} unless that 2nd file is extremely massive and so you don't want to create an entry in a[] for every line of it as you read it.
    – Ed Morton
    Mar 7, 2020 at 19:17
1
$ sed 's/:/s:$:/;s/$/:/' nums_file |
  sed -f - file

Explanation:

° 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. 

You must log in to answer this question.

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