Dies ist definitiv ein Fall, in dem Sie etwas verwenden möchten wie sed
(oder awk
oder perl
) anstatt in einer Shell-Schleife jeweils eine Zeile zu lesen. Dies ist nicht das, was die Shell gut oder effizient macht.
Sie könnten es nützlich finden, eine wiederverwendbare Funktion zu schreiben. Hier ist ein einfaches, aber es ist nicht auf funktionieren voll beliebigen Text (Schrägstriche oder einen regulären Ausdruck Metazeichen werden die Dinge verwirren):
function insertAfter # file line newText
{
local file="$1" line="$2" newText="$3"
sed -i -e "/^$line$/a"$'\\\n'"$newText"$'\n' "$file"
}
Beispiel:
$ cat foo.txt
Now is the time for all good men to come to the aid of their party.
The quick brown fox jumps over a lazy dog.
$ insertAfter foo.txt \
"Now is the time for all good men to come to the aid of their party." \
"The previous line is missing 'bjkquvxz.'"
$ cat foo.txt
Now is the time for all good men to come to the aid of their party.
The previous line is missing 'bjkquvxz.'
The quick brown fox jumps over a lazy dog.
$
, die nicht funktionieren; Sie benötigen einen Backslash und eine Newline in der sed-Befehlszeichenfolge nach dem 'a', nicht ein Leerzeichen. –