Как удалить определенный шаблон из определенных линий, используя Bash - PullRequest
0 голосов
/ 22 июня 2019

Я хочу удалить шаблон \textcolor{red}{ и заменить }} на } из списка определенных строк, используя bash. Допустим, у меня есть файл

cat A.txt

 \ParallelLText{\jverse{5}\textcolor{red}{“Ahut isi inut chili kerik abang chili rik damlo. Alangli chili kerik ahut penang achili ke tovar akungsi klolo, lapen la aphan dongpon long-lo lapen nampi avo atum vangsi chongthok-et-lo.}}{\jverse{5}\textcolor{red}{“A sower went out to sow his seed; and as he sowed, some fell on the path and was trampled on, and the birds of the air ate it up.}}
 \ParallelLText{\jverse{6}\textcolor{red}{Lapen akaprek achili ke longpak athak klolo, lapen lake kechingjok pen mamat chekedulo, pima hadak longle kecham avedet-lo.}}{\jverse{6}\textcolor{red}{Some fell on the rock; and as it grew up, it withered for lack of moisture. }}
 \ParallelLText{\jverse{7}\textcolor{red}{Akaprek achili ke ingsu kethe arong ajosi klolo, lapen ingsu kethe arong la pen the rap-rapsi la aphan petthip-lo.}}{\jverse{7}\textcolor{red}{Some fell among thorns, and the thorns grew with it and choked it.}}
 \ParallelLText{\jverse{8}\textcolor{red}{Jisu halatum aphan thak-lo, “Arnam Arat akepatu alam kechiniji, lake nangtum aphan nangpitang-lo, bonta akaprek atum aphan ke lamlir pensi thanlo. Lasi latum thek longbom setta thek longledetji lapen arjubom setta chini nedetji.” }}{\jverse{8}\textcolor{red}{He said, “To you it has been given to know the secrets of the kingdom of God; but to others I speak in parables, so that‘looking they may not perceive, and listening they may not understand.’}}
 \ParallelLText{\jverse{9}\textcolor{red}{“Bonta Lamlir athe lahelo: Chili ke Arnam alamlo.}}{\jverse{9}\textcolor{red}{“Now the parable is this: The seed is the word of God.}}
 \ParallelLText{\jverse{10}\textcolor{red}{Tovar akung keklo achili ke karjulong atumlo; latum kroikredetsi kejok kelongledetji aphan Diabol vangsi halatum aning arlo pen alam pondet-lo.}}{\jverse{10}\textcolor{red}{The ones on the path are those who have heard; then the devil comes and takes away the word from their hearts, so that they may not believe and be saved.}}

Допустим, у меня есть список строк для удаления шаблона: строка 1 и строка 3, поэтому мой окончательный результат после удаления и замены шаблона будет

 \ParallelLText{\jverse{5}“Ahut isi inut chili kerik abang chili rik damlo. Alangli chili kerik ahut penang achili ke tovar akungsi klolo, lapen la aphan dongpon long-lo lapen nampi avo atum vangsi chongthok-et-lo.}{\jverse{5}“A sower went out to sow his seed; and as he sowed, some fell on the path and was trampled on, and the birds of the air ate it up.}
 \ParallelLText{\jverse{6}\textcolor{red}{Lapen akaprek achili ke longpak athak klolo, lapen lake kechingjok pen mamat chekedulo, pima hadak longle kecham avedet-lo.}}{\jverse{6}\textcolor{red}{Some fell on the rock; and as it grew up, it withered for lack of moisture. }}
 \ParallelLText{\jverse{7}Akaprek achili ke ingsu kethe arong ajosi klolo, lapen ingsu kethe arong la pen the rap-rapsi la aphan petthip-lo.}{\jverse{7}Some fell among thorns, and the thorns grew with it and choked it.}
 \ParallelLText{\jverse{8}\textcolor{red}{Jisu halatum aphan thak-lo, “Arnam Arat akepatu alam kechiniji, lake nangtum aphan nangpitang-lo, bonta akaprek atum aphan ke lamlir pensi thanlo. Lasi latum thek longbom setta thek longledetji lapen arjubom setta chini nedetji.” }}{\jverse{8}\textcolor{red}{He said, “To you it has been given to know the secrets of the kingdom of God; but to others I speak in parables, so that‘looking they may not perceive, and listening they may not understand.’}}
 \ParallelLText{\jverse{9}\textcolor{red}{“Bonta Lamlir athe lahelo: Chili ke Arnam alamlo.}}{\jverse{9}\textcolor{red}{“Now the parable is this: The seed is the word of God.}}
 \ParallelLText{\jverse{10}\textcolor{red}{Tovar akung keklo achili ke karjulong atumlo; latum kroikredetsi kejok kelongledetji aphan Diabol vangsi halatum aning arlo pen alam pondet-lo.}}{\jverse{10}\textcolor{red}{The ones on the path are those who have heard; then the devil comes and takes away the word from their hearts, so that they may not believe and be saved.}}

Я пытался использовать эту команду, но этоне работает

VAR=\\texcolor{red}{
sed -i "1s/$VAR//;3s/$VAR//" A.txt

Я знаю, как удалить шаблон из всех линий, но я не знаю, для какой конкретной строки.

Ответы [ 2 ]

2 голосов
/ 22 июня 2019

Во-первых, сохранение строки в переменной без кавычек приводит к тому, что оболочка анализирует значение перед назначением переменной, поэтому одна из ваших обратных косых черт исчезнет уже к моменту назначения переменной.sed требуется две обратных косых черты, чтобы соответствовать буквенной обратной косой черте в регулярном выражении.Но самое простое решение здесь, вероятно, заключается в том, чтобы вообще не использовать переменную.

В sed нет способа обратиться к нескольким несмежным строкам;но простой обходной путь - это перечислить все строки и перейти к подпрограмме, если вы находитесь на любой из этих строк.

sed -i '
    1ba 
    3ba
    # Any other line, we are done
    b
:a
    s/\\textcolor{red}{//
    s/}}/}/' A.txt

На языке sed : объявляет буквенно-цифровую метку, а b label переходит на этот ярлык.Просто b переходит в конец скрипта.

(Как обычно, если вы работаете на платформе * BSD, включая MacOS, вам нужен -i '' с обязательным, но необязательным пустым аргументом.)

1 голос
/ 22 июня 2019

Попробуйте использовать одинарные кавычки вместо двойных, например:

sed '1s/\\textcolor{red}{//;3s/\\textcolor{red}{//'

Правила для одинарных и двойных кавычек различны: Разница между одинарными и двойными кавычками в Bash

Двойные кавычки будут интерпретировать символ обратной косой черты и заменят \\ на \ к тому времени, когда он перейдет к sed, поэтому sed увидит \t вместо \\t.

$  echo '\\'
\\
$ echo "\\"
\
...