Re: [問題] 刪除文字檔案中的換行符號

看板Perl作者時間14年前 (2010/01/07 08:52), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《RueyJing (瑞)》之銘言: : 我真的是翻書和上網找資料找到快瘋了也找不到.. : 我想將文字檔案中的某些換行符號刪去.. : 例如: : An apple a day , \n : keeps the doctor away \n : 我本來是寫 : while(<檔案>){ : chomp ; : s/An apple a day , \nkeeps the doctor away/ : An apple a day ,keeps the doctor away/gm ; : } : 但是卻怎樣都沒辦法出現我想要的結果 : 我有想過要把chomp拿掉..可是拿掉就會出現error訊息.. : 請大家幫幫忙教一下啊..我快抓狂了..今天一整天都在想這個問題.. 1. 先確定您的檔案要一行一行讀進來嗎?而且使用 \n 來區隔。 這樣 \n 只會在每行的最後面出現,經 chomp 處理完也應該不見了。 while (<ARGV>) { #chomp; print "[$_]"; } 2. 另外也可以考慮整個檔案都讀進來,再來做字串取代。 my $s = ''; READFILE: { local $/; $s = <ARGV>; } 3. 確定字串中是否會包含 \n,選擇合適的正規表示法來處理。 使用 Perl regexp 中的 modifiers,如 x、m、s、g 等, 像是 s/pattern/replacement/xms 或 s/pattern/replacement/gm。 且記得正確處理空白與換行符號。 m Multiline mode - ^ and $ match internal lines s match as a Single line - . matches \n x eXtended legibility - free whitespace and comments g Global - all occurrences 建議參考: 1. http://perldoc.perl.org/perlreref.html 2. perlre、perlreref -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.114.64.130

01/07 12:50, , 1F
perl -pi -e 's/(An apple a day , )\n/$1/g' 檔名
01/07 12:50, 1F
文章代碼(AID): #1BHJ1HPG (Perl)
文章代碼(AID): #1BHJ1HPG (Perl)