[英]How to delete \n from the end of some particular lines in file [shell]?
在Redhat中,我具有以下數據的file.csv:
170033101;20170302;;;"Free text 1"
170033101;20170302;;;"Free text 2"
170033101;20170302;;;"Free
text 3"
170033101;20170302;;;"Free text 4"
我要從文件中刪除錯誤的\\ n后創建另一個更正的文件(Correct_file.csv),如下所示:
170033101;20170302;;;"Free text 1"
170033101;20170302;;;"Free text 2"
170033101;20170302;;;"Free text 3"
170033101;20170302;;;"Free text 4"
我的解決方案:
我在下面的shell腳本中查找了不在以170開頭的行之前的行,然后創建了sed.txt,其中每個錯誤行都有sed行,以用空格替換\\ n。
我無法執行sed命令或tr命令來刪除基於行號的特定行
我的劇本:
>sed.txt;
for i in `grep -nv '^[1706]' $1|cut -f 1 -d \:`
do
if [ $i -eq 1 ]
then
continue
else
j=`expr $i - 1`
echo $j"s/\n//" >>sed.txt
fi
done
sed -f sed.txt $1 >$2
我調用腳本並傳遞2個參數1-舊文件2-新的更正文件,新文件與沒有更正的舊文件完全相同。
您可以使用以下awk
命令,該命令基於以下事實:行是否以"
結尾:
awk '!/"$/{p=$0; next} p!=""{$0 = p $0; p=""} 1' file
170033101;20170302;;;"Free text 1"
170033101;20170302;;;"Free text 2"
170033101;20170302;;;"Free text 3"
170033101;20170302;;;"Free text 4"
sed
返回新字符串,因此您無需echo
它。 只需將其稱為sed .. >> data.txt
以下sed語句將用新行替換掉新行。 您只需要傳遞要翻譯的行
sed ':a;N;$!ba;s/\n//g' <LINE INPUT>
如果將文件傳遞給它,它將循環讀取整個文件,並用空格替換換行符。
您可以使用此sed
:
sed '/^170/{:loop; N;/\n170/{P;D;t}; s/\n//g;b loop}' file
輸入:
$ cat file
170033101;20170302;;;"Free text 1"
170033101;20170302;;;"Free text 2"
170033101;20170302;;;"Free
text 3"
170033101;20170302;;;"Free
text
4"
測試:
$ sed '/^170/{:loop; N;/\n170/{P;D;t}; s/\n//g;b loop}' file > correct_file.csv
170033101;20170302;;;"Free text 1"
170033101;20170302;;;"Free text 2"
170033101;20170302;;;"Free text 3"
170033101;20170302;;;"Free text 4"
當我想使用\\n
我更喜歡簡單的perl而不是sed:
$ cat file1
170033101;20170302;;;"Free text 1"
170033101;20170302;;;"Free text 2"
170033101;20170302;;;"Free
text 3"
170033101;20170302;;;"Free text 4"
$ perl -pe 's/[^"]\n/ /g' file1
170033101;20170302;;;"Free text 1"
170033101;20170302;;;"Free text 2"
170033101;20170302;;;"Free text 3"
170033101;20170302;;;"Free text 4"
該perl oneliner會在每行新行中用一個空格替換\\n
而不用引號引起來"
PS:您可以添加>newfile
在命令結束發送“糾正”輸出到newfile
,也可以代替使用甚至編輯當前文件-i
perl的開關。
嘗試跟隨awk一次。
awk '{printf("%s%s",$0 !~ /^[0-9]+/?"":(NR>1?RS:""),$0)} END{print ""}' Input_file
檢查此處是否有任何不是從數字開始的行,然后通過RS(記錄分隔符)在此處打印新行,以確保它不應該出現在第一行,否則什么也不打印。 在awk的END部分中打印NULL,最后將打印新行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.