Mar*_*jer 1 unix linux shell awk sed
下面是我逗号分隔的input.txt文件,我想读取列并在任何1列有空格时将行写入output.txt.
内容input.txt:
1,Hello,world
2,worl d,hell o
3,h e l l o, world
4,Hello_Hello,World@c#
5,Hello,W orld
Run Code Online (Sandbox Code Playgroud)
内容output.txt:
1,Hello,world
4,Hello_Hello,World@c#
Run Code Online (Sandbox Code Playgroud)
是不是可以实现使用awk?请帮忙!
Sto*_*ica 11
使用空格过滤掉行的简单方法是使用反向匹配grep:
grep -v ' ' input.txt
Run Code Online (Sandbox Code Playgroud)
如果你必须使用awk:
awk '!/ /' input.txt
Run Code Online (Sandbox Code Playgroud)
或者perl:
perl -ne '/ / || print' input.txt
Run Code Online (Sandbox Code Playgroud)
或纯粹bash:
while read line; do [[ $line == *' '* ]] || echo $line; done < input.txt
# or
while read line; do [[ $line =~ ' ' ]] || echo $line; done < input.txt
Run Code Online (Sandbox Code Playgroud)
UPDATE
要检查是否让字段2包含空格,您可以这样使用awk:
awk -F, '$2 !~ / /' input.txt
Run Code Online (Sandbox Code Playgroud)
要检查是否让字段2或字段3包含空格:
awk -F, '!($2 ~ / / || $3 ~ / /)' input.txt
Run Code Online (Sandbox Code Playgroud)
对于您在评论中的后续问题
为了做同样的事情sed,我只知道这些尴尬的解决方案:
# remove lines if 2nd field contains space
sed -e '/^[^,]*,[^,]* /d' input.txt
# remove lines if 2nd or 3rd field contains space
sed -e '/^[^,]*,[^,]* /d' -e '/^[^,]*,[^,]*,[^,]* /d' input.txt
Run Code Online (Sandbox Code Playgroud)
对于您在评论中的第二个后续问题
要忽略第2或第3个字段中的前导空格:
awk -F', *' '!($2 ~ / / || $3 ~ / /)' input.txt
# or perhaps what you really want is this:
awk -F', *' -v OFS=, '!($2 ~ / / || $3 ~ / /) { print $1, $2, $3 }' input.txt
Run Code Online (Sandbox Code Playgroud)