[英]Find and delete lines with multiple words in a text file
如果文本文件中有多个单词,如何制作bash脚本来删除行?
也许是这样的:
#!/bin/bash
exec 3>output
while read -r line; do
nwords=`echo $line | wc -w`;
if [ ! "$nwords" -gt 1 ]; then
echo "$line" >&3;
fi
done < input
exec 3>&-
这样,您将在输出文件中包含所有不超过word的行,并且可以删除输入文件than和mv输出到输入。
我用sed来做这个:我的txt文件是file.txt:
one
one two
one two tree for
one two
sed -i.bck '/\(.\+\)\(\s\+\)\(.*\)/d' file.txt
cat file.txt
one
如果您的单词由“ 空格 ”字符分隔,则可以使用sed在一行中完成。 让“ ./myfile.txt ”作为您的文件名,然后:
#!/bin/bash
sed -i "/[^ ][ ]/d" ./myfile.txt
正则表达式替换所有以非空格字符开头的空格字符,当您有两个单词时就是这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.