0

I need to use sed to:

Replace Strings Such as:

tr("Text");

TO

"text";

tr("Textfsafasfsfas safasdfsafas");

TO

"Textfsafasfsfas safasdfsafas";

foo(tr("text")); TO foo("text");

Do Not Replace these Strings:

tr("text").arg(text);

tr("I am some text") .arg(i do stuff);

tr("I am some text") .arg(i do stuff) .arg(I also do stuff);

where it needs to be handled from 1 up to n lines of this.

My current code does not cover the multi-line .arg edge case. Any bright ideas?

Current sed code:

sed -i '/\btr(/{ :a; s/\btr(\([^)]*\))\([^.]\)/\1\2/I; t; N; ba}' $file_t

Edit:

errors << tr("Error: Encountered an invalid token at line: %1, column: %2.") .arg(m_reader.lineNumber()) .arg(m_reader.columnNumber());

is an edge-case that is still an issue at this time.

2
  • it seems like the only reason why this needs to be multiline is due to the .arg() usage. Can you do this in two passes? Aug 31, 2016 at 14:45
  • As it stands right now, regardless if I have .arg not on the first line the tr with paren. will be deleted. It would be more trouble than it's worth trying to put that back in on the second pass
    – Klamz
    Aug 31, 2016 at 14:51

1 Answer 1

1
$ cat ip.txt 
tr("Text");

tr("Textfsafasfsfas
safasdfsafas");

foo(tr("text"));

tr("text").arg(text);

tr("I am some text")
.arg(i do stuff);

tr("I am some text")
.arg(i do stuff)
.arg(I also do stuff);

tr("I am some text")
    .arg(i do stuff);

If file is small enough to hold in memory after slurping all lines as single string,

$ perl -0777 -pe 's/\btr\(([^)]+)\)(?!\s*.arg)/$1/g' ip.txt 
"Text";

"Textfsafasfsfas
safasdfsafas";

foo("text");

tr("text").arg(text);

tr("I am some text")
.arg(i do stuff);

tr("I am some text")
.arg(i do stuff)
.arg(I also do stuff);

tr("I am some text")
    .arg(i do stuff);

If the output is okay, add the -i or -i.bak option for inplace editing

Edit:

Thanks @Costas for pointing out that \n?\s* can be reduced to \s*

1
  • 2
    \n?\s* can be replaced by [:space:]*
    – Costas
    Aug 31, 2016 at 15:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .