Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string after semicolon

Tags:

bash

sed

awk

I have a file filtered_content with the following 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

and another file converted_data with content:

1624684050
1634015250
1614661650
1622005650

I want to replace strings after semicolon in filtered_content with content of converted_data like this:

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

I tried something like this, but doesn't work.

data=$(cat /tmp/converted_data)
cat /tmp/filtered_content | sed 's/;.*//' | sed 's/.${data};//'
like image 592
bmoreira18 Avatar asked Mar 09 '26 20:03

bmoreira18


2 Answers

You may consider this awk solution:

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

A more readable form:

awk '
BEGIN { FS=OFS=";" }
NR == FNR {
   arr[FNR] = $1
   next
}
{
   $2 = arr[FNR]
} 1' converted_data filtered_content
like image 112
anubhava Avatar answered Mar 11 '26 10:03

anubhava


A quick way using paste and cut and Process Substitution.

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

As per @oguzismail's comment, a Process Substitution is not needed.

cut -d ';' -f1 filtered_content.txt | paste -d';' - converted_content.txt
like image 26
Jetchisel Avatar answered Mar 11 '26 09:03

Jetchisel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!