2017-10-20 157 views
0

我面對的東西,看起來容易的當前行,但無法找到答案:刪除文件

該功能的目的是去除所有包含3個逗號「」行:

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

我沒有找到如何刪除當前行,你能幫助我嗎?

我從grep中抽取這個tmp.txt,如果它是一個變量而不是tmp.txt它會是一樣嗎?

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" 

在此先感謝

回答

0

我會在其他方式都做到了:

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

如果線路匹配,保持它,否則到下一行。

3

使用sed命令唯一的解決方案。

sed '/^\([^,]*,\)\{3\}[^,]*$/d' infile 
  • 刪除所有那些字符逗號,究竟發生了3次線。

或者使用awk

awk -F, 'NF!=4' infile 

或者兩者皆是從變量讀取。

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

這個簡單的命令可以去除所有的線,它包含3

$ awk '!/3/' file_name

+1

不'3'本身性格逗號','並且只有在發生它的3倍線。 –

2

簡單AWK溶液

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

gsub替換用指定的字符串並且它的圖案返回替換/替換的數量。

我們在這裏用,替換,,因此gsub將返回字符串中的,的數字。

例子:

輸入文件

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

輸出

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