lotusnoir
lotusnoir

Reputation: 57

Removing current line of a file

I'm facing something that looks easy, but can't find the answer :

The goal of this function is to remove all the line that contains 3 commas ',' :

while read line; do                                                                                                    
        COUNT=$(echo $line | grep -o "\," | wc -)
        if [ $COUNT -ne 3 ]; then
               remove line
        fi
done < tmp.txt

I dont find how to remove current line, can you help me ?

I extract this tmp.txt from a larger with grep, if it was in a variable instead of a tmp.txt will it be the same ?

while read line; do
COUNT=$(echo $line | grep -o "\," | wc -)
       COUNT=$(echo $line | grep -o "\," | wc -)
        if [ $COUNT -ne 3 ]; then
               remove line
        fi
done <<< "$toto"

Thanks in advance

Upvotes: 0

Views: 204

Answers (4)

Rahul Verma
Rahul Verma

Reputation: 3089

A simple awk solution

awk 'gsub(/,/,",")!=3' file

gsub replaces the pattern with the specified string and it returns the number of substitutions/replacements made.

We are replacing , with , here and thus gsub will return us the number of , in the string.

Example :

Input file

hello this line has 1 ,
This line, has, 3 ,
This line, has, 4 , commas , Thanks

Output

$ awk 'gsub(/,/,",")!=3' file
hello this line has 1 ,
This line, has, 4 , commas , Thanks

Upvotes: 2

αғsнιη
αғsнιη

Reputation: 2761

Using sed command only solution.

sed  '/^\([^,]*,\)\{3\}[^,]*$/d' infile
  • Delete all those line which character comma , occurred exactly 3 times.

Or using awk:

awk -F, 'NF!=4' infile

Or both read from a variable.

sed  '/^\([^,]*,\)\{3\}[^,]*$/d' <<<"$variable"
awk -F, 'NF!=4' <<<"$variable"

Upvotes: 4

Ratul
Ratul

Reputation: 451

This simple command can remove all the lines that contains 3

$ awk '!/3/' file_name

Upvotes: -1

Will
Will

Reputation: 2410

I would have done it in the other way :

while read line; do                                                                                                    
        COUNT=$(echo $line | grep -o "\," | wc -)
        if [ $COUNT -eq 3 ]; then
               echo $line >> $tempofile
        fi
done < tmp.txt

If the line is matched, keep it, otherwise get to next line.

Upvotes: 0

Related Questions