分号后替换字符串

我有一个filtered_content包含以下内容的文件:

ip-172-31-42324-162.sa-east-1.compute.internal;2021-06-26T05:07:30Z
ip-172-31-42324-162.sa-east-1.compute.internal;2021-10-12T05:07:30Z
ip-172-31-4234-163.sa-east-1.compute.internal;2021-03-02T05:07:30Z
ip-172-31-4234-163.sa-east-1.compute.internal;2021-05-26T05:07:30Z

和另一个converted_data包含内容的文件:

1624684050
1634015250
1614661650
1622005650

我想filtered_content用这样的内容替换分号后的字符串converted_data

ip-172-31-42324-162.sa-east-1.compute.internal;1624684050
ip-172-31-42324-162.sa-east-1.compute.internal;1634015250
ip-172-31-4234-163.sa-east-1.compute.internal;1614661650
ip-172-31-4234-163.sa-east-1.compute.internal;1622005650

我试过这样的事情,但没有用。

data=$(cat /tmp/converted_data)
cat /tmp/filtered_content | sed 's/;.*//' | sed 's/.${data};//'

回答

使用pasteandcut和Process Substitution 的快速方法。

paste -d';' <(cut -d';' -f1 filtered_content.txt) converted_content.txt

根据@oguzismail 的评论,不需要进程替换。

cut -d ';' -f1 filtered_content.txt | paste -d';' - converted_content.txt


回答

你可以考虑这个awk解决方案:

awk 'BEGIN{FS=OFS=";"} NR==FNR {arr[FNR]=$1; next} {$2 = arr[FNR]} 1' converted_data filtered_content

ip-172-31-42324-162.sa-east-1.compute.internal;1624684050
ip-172-31-42324-162.sa-east-1.compute.internal;1634015250
ip-172-31-4234-163.sa-east-1.compute.internal;1614661650
ip-172-31-4234-163.sa-east-1.compute.internal;1622005650

更易读的形式:

awk '
BEGIN { FS=OFS=";" }
NR == FNR {
   arr[FNR] = $1
   next
}
{
   $2 = arr[FNR]
} 1' converted_data filtered_content


回答

您根本不需要converted_data,只需单独使用 GNU awk(formktime()gensub()filtered_content

$ awk 'BEGIN{FS=OFS=";"} {$NF=mktime(gensub(/[-T:]/," ","g",$NF),1)} 1' filtered_content
ip-172-31-42324-162.sa-east-1.compute.internal;1624684050
ip-172-31-42324-162.sa-east-1.compute.internal;1634015250
ip-172-31-4234-163.sa-east-1.compute.internal;1614661650
ip-172-31-4234-163.sa-east-1.compute.internal;1622005650

  • Obviously this is the correct answer.
  • Yep, we gave the OP. what he wants but this answer is what he really needs.

以上是分号后替换字符串的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>