![](/img/trans.png)
[英]copy a part of a line from file1 to specific place in file2 using sed or any other command
[英]How can I append values to each line in file1 after using part of that line to index into file2 and lookup the value?
我基本上有以下2個文件:
$ cat file1.txt
AB,12 34 56,2.4,256,,
CD,23 45 67,10.8,257,,
EF,34 56 78,0.6,258,,
GH,45 67 89,58.3,259,,
...
$ cat file2.txt
AB,12 34 56,2.4,36
XY,56 99 11,3.6,15
ZQ,12 36 89,5.9,0
EF,34 56 78,0.6,99
GH,45 67 89,58.3,79
...
對於 file1.txt 中的每一行,我想使用前 3 個字段作為 file2.txt 中的索引,獲取相應的最后一個字段,並將其放入 file1.txt 中,如下所示:
cat newfile.txt
AB,12 34 56,2.4,256,36,
CD,23 45 67,10.8,257,,
EF,34 56 78,0.6,258,99,
GH,45 67 89,58.3,259,79,
不能保證 file1 中的每一行都會出現在 file2 中,反之亦然,對於這種情況,上面 newfile.txt 中顯示的空字段是可以的。
在我的第一次嘗試中,我在一個while read
循環中從 file1 中讀取每一行,然后在 file2 中查找適當的行,它可以工作,但它太慢了。 file1 和 file2 各有數十萬行。
有什么方法可以使用 sed 將 file1 中每行的前 3 個字段用作 file2 的索引,查找我需要的值,然后將 append 使用到 file1 中的那一行? 這樣做沒有逐行讀取file1?
任何幫助表示贊賞。
使用join
和sed
(用於一些預處理和后處理),並假設|
字符沒有出現在兩個文件中
join -a1 -t'|' \
<(sort file1.txt | sed 's/,/|/3') \
<(sort file2.txt | sed 's/,/|/3') |
sed 's/,|//; s/|/,/; s/[^,]$/&,/' > newfile.txt
(使用問題中給出的輸入進行測試)
可以使用關聯 arrays 在普通bash
中完成,但我懷疑它是否有效。 例如:
#!/bin/bash
declare -A tail
while IFS= read -r line; do
if [[ $line =~ ([^,]*,){3} ]]; then
tail[${BASH_REMATCH[0]}]=${line#"${BASH_REMATCH[0]}"}
fi
done < file2.txt
while IFS= read -r line; do
if [[ $line =~ ([^,]*,){3} ]] && [[ -n ${tail[${BASH_REMATCH[0]}]} ]]; then
printf '%s%s\n' "${line%?}" "${tail[${BASH_REMATCH[0]}]},"
else
printf '%s\n' "$line"
fi
done < file1.txt > newfile.txt
使用 awk:
awk -F, 'FNR==NR { map[$1","$2","$3]=$4;next } { print $1","$2","$3","$4","map[$1","$2","$3]"," }' file2.txt file1.txt
首先處理file1.txt (FNR==NR) 創建一個數組map,第一個、第二個和第三個逗號分隔的字段作為索引,第四個字段作為值。 然后對於第二個文件,打印第一個、第二個、第三個和第四個字段以及第一個索引的 map 數組的內容,用逗號分隔。
這將在每個 Unix 框中的任何 shell 中使用任何 awk 非常有效地工作,並且不依賴於輸入中不存在的任何字符:
$ awk '
BEGIN { FS=OFS="," }
{ key = $1 FS $2 FS $3 }
NR==FNR { map[key] = $4; next }
{ $5 = map[key] }
1' file2 file1
AB,12 34 56,2.4,256,36,
CD,23 45 67,10.8,257,,
EF,34 56 78,0.6,258,99,
GH,45 67 89,58.3,259,79,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.