bash 使用批处理从匹配字符串的行中删除文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14095048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove text from lines matching string using batch
提问by BearCode
I need to remove the text from the lines that contain a specific string using batch processors: SED, AWK, Windows batch, Unix shell or something similar. If the string is "green" then the following input
我需要使用批处理器从包含特定字符串的行中删除文本:SED、AWK、Windows 批处理、Unix shell 或类似的东西。如果字符串是“绿色”,则以下输入
red
green 1
blue
green 2
yellow
will produce the output
将产生输出
red
<EMPTY LINE>
blue
<EMPTY LINE>
yellow
I also need to do the same thing for lines not matching the string, producing the output
我还需要对不匹配字符串的行做同样的事情,产生输出
<EMPTY LINE>
green 1
<EMPTY LINE>
green 2
<EMPTY LINE>
I need to remove text from lines (empty the content of lines), not to delete them.
我需要从行中删除文本(清空行的内容),而不是删除它们。
回答by perreal
Using sed to empty lines containing green:
使用 sed 到包含green以下内容的空行:
sed '/green/s/.*//' input
And using sed to empty other lines:
并使用 sed 清空其他行:
sed '/green/!s/.*//' input
回答by David Ruhmann
Windows Command Line/Batch
Windows 命令行/批处理
Output non matching lines
输出非匹配行
find /V "green" file.txt
Output matching lines
输出匹配线
find "green" file.txt
These commands will output the content to the console. Redirect the output to destination files as needed. Example:
这些命令会将内容输出到控制台。根据需要将输出重定向到目标文件。例子:
find /V "green" file.txt > nonmatchingoutput.txt
Type find /?or findstr /?for help and all the options.
键入find /?或findstr /?寻求帮助和所有选项。
Updatefor updated question.
更新更新的问题。
This will do what you ask using only Batch
这将只使用 Batch 完成您的要求
:: Hide Commands
@echo off
:: Erase Existing Files
>match.txt ( <nul set /p "=" )
>nomatch.txt ( <nul set /p "=" )
:: Loop through Source and Generate Output
for /f "tokens=1,* delims=]" %%K in ('type temp.txt ^| find /V /N ""') do (
for /f "delims=" %%X in ('echo(%%L ^| find /V "green"') do (
echo(%%X>>nomatch.txt
echo.>>match.txt
)
for /f "delims=" %%X in ('echo(%%L ^| find "green"') do (
echo(%%X>>match.txt
echo.>>nomatch.txt
)
)
回答by Debaditya
Sed solutions are listed below:
下面列出了 Sed 解决方案:
Input.txt
输入.txt
red
green 1
blue
green 2
yellow
Try This
尝试这个
Code 1 :
代码 1:
$> grep -v green Input.txt | sed G
or
或者
$> sed '!s/^green//g' Input.txt
red
blue
yellow
Code 2 :
代码 2:
$> grep green Input.txt | sed G
or
或者
$> sed -n '/green/p' Input.txt
green 1
green 2
回答by fge
Using perl:
使用 perl:
# Empty when finding green
perl -pe 's,.*,, if /green/' inputfile
# Empty when not finding green
perl -pe 's,.*,, unless /green/' inputfile
These commands will output the content to stdout, so redirect the output to the destination files.
这些命令会将内容输出到 stdout,因此将输出重定向到目标文件。

