Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed copy substring in following line

Tags:

sed

po

I've a .po file I need to copy msgid value into msgstr value if msgstr is empty.

For example

msgid "Hello"
msgstr ""

msgid "Dog"
msgstr "Cane"

Should become

msgid "Hello"
msgstr "Hello"

msgid "Dog"
msgstr "Cane"

Currently, for testing purpose, I'm working with another file, but final script will works inline.

#!/bin/bash
rm it2.po
sed $'s/^msgid.*/&\\\n---&/' it.po > it2.po
sed -i '/^msgstr/d' it2.po
sed -i 's/^---msgid/msgstr/' it2.po

This script has 2 problems (at least):

  1. copies msgid into msgstr also when msgstr is not empty;
  2. I'm pretty sure that exist a single line or a more elegant solution.

Any help would be appreciated. Thanks in advance.

like image 372
assistbss Avatar asked Jun 01 '21 07:06

assistbss


Video Answer


2 Answers

You may consider better tool gnu awk instead of sed:

awk -i inplace -v FPAT='"[^"]*"|\\S+' '$id != "" && $1 == "msgstr" && (NF==1 || $2 == "\"\"") {$2=id} $1 == "msgid" {id=$2} 1' file

msgid "Hello"
msgstr "Hello"

msgid "Dog"
msgstr "Cane"

-v FPAT='"[^"]*"|\\S+' makes a quoted string or any non-whitespace field an individual field.

A more readable form:

awk -i inplace -v FPAT='"[^"]*"|\\S+' '
$id != "" && $1 == "msgstr" && (NF==1 || $2 == "\"\"") {$2=id}
$1 == "msgid" {id=$2}
1' file
like image 79
anubhava Avatar answered Oct 20 '22 23:10

anubhava


This might work for you (GNU sed):

sed -E 'N;s/(msgid "(.*)".*msgstr )""/\1"\2"/;P;D' file

Open a two line window and if the first line contains msgid and the second msgstr "", replace the msgstr value by the msgid value. Print/delete the first line and repeat.

like image 27
potong Avatar answered Oct 20 '22 22:10

potong