简体   繁体   中英

Bash script to remove lines containing more than one word while maintaining any whitespaces (alginment)

Example:

[tab][space]Stays

Stays2[space][tab]

this-line-will-also-stay

this line will not stay

I've tried using: sed '/ /d' and: while read ab; do if [ -z "$b" ] while read ab; do if [ -z "$b" ]

However the white spaces get removed and no alignment is kept. Any help would be appreciated.

You want to match a space that comes after a non-space:

sed '/[^ ] /d'

Or more robust:

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

perl to use more powerful regular expressions than sed gives you:

$ perl -ne 'print if /^\s*\S+\s*$/' input.txt
     Stays
Stays2  
this-line-will-also-stay

Any line that starts with 0 or more leading whitespace characters, 1 or more non-whitespace characters, and 0 or more whitespace characters at the end will be printed. Anything else will be ignored.


You can do the same in sed but it's a bit more cumbersome due to basic regular expressions:

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

You want to remove all lines where there are at least 2 non-whitespace chars separated with 1+ whitespace chars:

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

See the online demo :

s="  Stays
Stays2  
this-line-will-also-stay
this line will not stay"

sed '/[^[:space:]][[:space:]]\{1,\}[^[:space:]]/d' <<< "$s"

Output:

     Stays
Stays2  
this-line-will-also-stay

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM