簡體   English   中英

使用awk按行數將行移動到文件中

[英]move lines into a file by number of columns using awk

我有一個帶有'|| o ||'的示例文件 作為字段分隔符。

www.google.org||o||srScSG2C5tg=||o||bngwq
farhansingla.it||o||4sQVj09gpls=||o||
ngascash||o||||o||
ms-bronze.com.br||o||||o||

我想在1.txt只移動一個字段,在not_1.txt只移動一個字段。 我使用以下命令:

sed  's/\(||o||\)\+$//g' sample.txt  | awk -F '[|][|]o[|][|]' '{if (NF == 1) print > "1.txt"; else print > "not_1.txt" }'

問題是它不是原始線而是移動線。

我得到的輸出是(not_1.txt):

td@the-end.org||o||srScSG2C5tg=||o||bnm
erba01@tiscali.it||o||4sQVj09gpls=

1.TXT:

ngas
ms-inside@bol.com.br

如您所見,原始線條已被修改。 我不想修改這些行。 任何幫助將受到高度贊賞。

Awk解決方案:

awk -F '[|][|]o[|][|]' \
'{ 
     c = 0; 
     for (i=1; i<=NF; i++) if ($i != "") c++;
     print > (c == 1? "1" : "not_1")".txt"  
 }' sample.txt

結果:

$ head 1.txt not_1.txt 
==> 1.txt <==
ngascash||o||||o||
ms-bronze.com.br||o||||o||

==> not_1.txt <==
www.google.org||o||srScSG2C5tg=||o||bngwq
farhansingla.it||o||4sQVj09gpls=||o||

以下awk可以幫助你。

awk -F'\\|\\|o\\|\\|' '{for(i=1;i<=NF;i++){count=$i?++count:count};if(count==1){print > "1_field_only"};if(count>1){print > "not_1_field"};count=""}'  Input_file

現在也添加非單一襯里形式的解決方案。

awk -F'\\|\\|o\\|\\|' '
{
  for(i=1;i<=NF;i++){ count=$i?++count:count };
  if(count==1)      { print > "1_field_only" };
  if(count>1)       { print > "not_1_field"  };
  count=""
}
'   Input_file

說明:現在也為上面的代碼添加說明。

awk -F'\\|\\|o\\|\\|' '                          ##Setting field separator as ||o|| here and escaping the | here to take it literal character here.
{
  for(i=1;i<=NF;i++){ count=$i?++count:count };  ##Starting a for loop to traverse through all the fields here, increasing variable count value if a field is NOT null.
  if(count==1)      { print > "1_field_only" };  ##Checking if count value is 1 it means fields are only 1 in line so printing current line into 1_field_only file.
  if(count>1)       { print > "not_1_field"  };  ##Checking if count is more than 1 so printing current line into output file named not_1_field file here.
  count=""                                       ##Nullifying the variable count here.
}
' Input_file                                     ##Mentioning Input_file name here.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM