2つの文字列間の改行文字を置き換える

2つの文字列間の改行文字を置き換える

問題が発生したため、1つの例外を除き、適切な質問の1つであなたの回答を確認しました。

これが私が達成したいものです。 \n が 2 つの\"文字列の間にある場合は、\n (改行文字) を空白に置き換える必要がありますが、1 つの例外を除いて|別の文字列の前に見つかった場合は\"何も起こりません。

以下は私の入力/出力の例です。

Input 1
test \" data
get this line\" in above line

Output 1
test \" dataget this line\" in above line

Input2
test \" data
keep| this line\" here

Output 2
test \" data
keep| this line\" here

次のコマンドを実行すると、入力1ではほとんど機能しますが、入力2では正しい結果が得られません。

perl -pe 's/\n(?=(?:(?!\\"|\\").)*(\\"|\n|))/\1/g' input1.txt
test \" dataget this line\" in above line[sh]$

perl -pe 's/\n(?=(?:(?!\\"|\\").)*(\\"|\n|))/\1/g' input2.txt
test \" dataget this line\" in above line[sh]$

上記の2つの入力では、「data」の後にキャリッジリターンがあります。つまり、「data」の後のテキストは次の行にありますが、この投稿では次の行でそれを見ることはできません。このコマンドを調整するのに役立ちます。

ベストアンサー1

次のPerlシングルライナーを試してみてください。

perl -00pe 's/(\\"(?:(?!\\"|\|).)*)\n((?:(?!\\"|\|).)*\\")/\1\2/g' file

例:

$ cat file
test \" data
get this line\" in above line

test \" data
keep| this line\" here
$ perl -00pe 's/(\\"(?:(?!\\"|\|).)*)\n((?:(?!\\"|\|).)*\\")/\1\2/g' file
test \" dataget this line\" in above line

test \" data
keep| this line\" here

説明する:

(                        group and capture to \1:
  \\                       '\'
  "                        '"'
  (?:                      group, but do not capture (0 or more
                           times):
    (?!                      look ahead to see if there is not:
      \\                       '\'
      "                        '"'
     |                        OR
      \|                       '|'
    )                        end of look-ahead
    .                        any character except \n
  )*                       end of grouping
)                        end of \1
\n                       '\n' (newline)
(                        group and capture to \2:
  (?:                      group, but do not capture (0 or more
                           times):
    (?!                      look ahead to see if there is not:
      \\                       '\'
      "                        '"'
     |                        OR
      \|                       '|'
    )                        end of look-ahead
    .                        any character except \n
  )*                       end of grouping
  \\                       '\'
  "                        '"'
)                        end of \2

おすすめ記事