如何将这个sed命令应用于文本文件中的特定行而不是整个文件?
我在这里找到了一种解决方案,可以用特定的地址替换文件中的任何IP地址。我需要将此命令应用于文件中的特定行,以便它仅替换一个未知IP地址。我看到sed使用-n进行过滤,但是我对如何应用它来实现我的目标一无所知。
此代码适用于文件中的每个IP:
sed -e 's/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/x.x.x.x/g' test.txt
我如何将其应用于文件中唯一包含字符串“ ipv4”的行,以使包含IP地址的其他行保持不变?
答案 0 :(得分:1)
<mat-form-field class="field-sizing">
<input matInput required placeholder="{{ 'REGISTRATION.COUNTRY' | translate }}" name="country"
id="country" [matAutocomplete]="auto" formControlName="country"
[ngClass]="{ 'is-invalid': g.country.touched && g.country.errors }" />
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredCountries | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
<mat-error class="invalid-feedback"
*ngIf="g.country.touched && g.country.errors && g.country.errors.required">
{{ 'REGISTRATION.COUNTRY' | translate }} {{ 'VALIDATION.REQUIRED' | translate }}
</mat-error>
</mat-form-field>
如果您未指定sed -re '/ipv4/s/[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}/x.x.x.x/g' test.txt
,则需要转括号,即:
-r
答案 1 :(得分:0)
您可以跳过无趣的行:
sed '/ipv4/!b;s/YOUR PATTERN HERE/YOUR IP HERE/' input
答案 2 :(得分:0)
如果我做对了,您想在也包含ipv4
的行中找到该IP地址的第一个匹配项,并跳过所有其他匹配项。
使用GNU sed,尝试
sed -i -E '/ipv4/{s/[0-9]{1,3}(\.[0-9]{1,3}){3}/x.x.x.x/g;T;:a;n;ba}' test.txt
-E
将启用POSIX ERE语法,无需转义{}
和()
。 -i
将直接替换文件中的内联。 /ipv4/
将找到一行上带有ipv4
的行,然后{s/[0-9]{1,3}(\.[0-9]{1,3}){3}/x.x.x.x/g;T;:a;n;ba}
将仅在该行上进行替换。参见potong's explanation of the T;:a;n;ba
here
如果您拥有POSIX sed
,请尝试
sed -e '/ipv4/ {' -e 's/[0-9]\{1,3\}\(\.[0-9]\{1,3\}\)\{3\}/x.x.x.x/g' -e ':a' -e n -e 'ba' -e '}' file > newfile