如果文本文件中有多个单词,如何制作bash脚本来删除行?
Maybe something like that:
#!/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>&-
Then you will have all lines which don't have more than word in output file and you can delete input file than and mv output to input.
I used this, using sed: my txt file is file.txt:
one
one two
one two tree for
one two
sed -i.bck '/\(.\+\)\(\s\+\)\(.*\)/d' file.txt
cat file.txt
one
If your words are separated by a " space " character you can do it in just one line, with sed . Let " ./myfile.txt " be your file name, then:
#!/bin/bash
sed -i "/[^ ][ ]/d" ./myfile.txt
The regex replace all space characters preceded by a non space characters, that is the case when you have two words.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.