Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex Bash脚本删除包含多个单词的行,同时保留任何空格(可选)_Regex_Linux_Bash - Fatal编程技术网

Regex Bash脚本删除包含多个单词的行,同时保留任何空格(可选)

Regex Bash脚本删除包含多个单词的行,同时保留任何空格(可选),regex,linux,bash,Regex,Linux,Bash,例如: [选项卡][空格]停留 Stays2[空间][选项卡] 这条线也将保持不变 这条线不会停 我试过使用: sed'//d' 以及: 读取a b时;如果[-z“$b”] 但是,将删除空白,并且不保持对齐。 任何帮助都将不胜感激。您希望匹配非空格后面的空格: sed '/[^ ] /d' 或更稳健: sed '/[^[:space:]][[:space:]]/d' perl可以使用比sed更强大的正则表达式: $ perl -ne 'print if /^\s*\S+\s*$/' in

例如:

[选项卡][空格]停留

Stays2[空间][选项卡]

这条线也将保持不变

这条线不会停

我试过使用:
sed'//d'
以及:
读取a b时;如果[-z“$b”]

但是,将删除空白,并且不保持对齐。
任何帮助都将不胜感激。

您希望匹配非空格后面的空格:

sed '/[^ ] /d'
或更稳健:

sed '/[^[:space:]][[:space:]]/d'

perl可以使用比sed更强大的正则表达式:

$ perl -ne 'print if /^\s*\S+\s*$/' input.txt
     Stays
Stays2  
this-line-will-also-stay
将打印以0个或多个前导空白字符、1个或多个非空白字符和0个或多个结尾空白字符开头的任何行。其他任何事情都将被忽略


您可以在sed中执行相同的操作,但由于基本正则表达式的存在,这有点麻烦:

$ sed -n '/^[[:space:]]*[^[:space:]]\{1,\}[[:space:]]*$/p' input.txt
     Stays
Stays2  
this-line-will-also-stay

要删除至少有2个非空白字符与1+空白字符分隔的所有行:

sed '/[^[:space:]][[:space:]]\{1,\}[^[:space:]]/d' file
见:


当你说对齐时,你是指缩进吗?@Shloim是的,这就是我的意思:)
匹配除了新行以外的任何东西,所以它也会匹配空格字符,如果你想使用非空格用法
\s
我想要:
sed
中的@code疯狂,
甚至匹配模式空间中的新行
\S
仅在GNU
sed
@Shloim中受支持。如果行的开头有空格或制表符,我不确定这是否有效。此sed将删除非空格之后包含空格的任何行。所以前导空格不会被删除。考虑到我们采取了相反的方法,这两个REs是多么的相似,这很有趣。@Shawn POSIX ERE也可以被使用,然后
+
可以被用作量词:
sed-E'/[^[:space:][[:space:]+[^[:space:]]/d'文件“
这不是标准的,甚至不是可移植的——IIRC,gnu-sed使用
-r
,如果像AIX这样的商业unix支持这两种选择,我会感到惊讶。(当然,OP确实提出了一个问题linux…@Shawn我知道,我只在linux中工作,所以我习惯了
-E
和GNU
sed
)。
s="  Stays
Stays2  
this-line-will-also-stay
this line will not stay"

sed '/[^[:space:]][[:space:]]\{1,\}[^[:space:]]/d' <<< "$s"
     Stays
Stays2  
this-line-will-also-stay