![줄 번호를 기준으로 파일에 열 추가](https://rvso.com/image/168800/%EC%A4%84%20%EB%B2%88%ED%98%B8%EB%A5%BC%20%EA%B8%B0%EC%A4%80%EC%9C%BC%EB%A1%9C%20%ED%8C%8C%EC%9D%BC%EC%97%90%20%EC%97%B4%20%EC%B6%94%EA%B0%80.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.