2011-03-14 50 views
1

我MYFILE如下如何刪除行方含在UNIX從文件字符串或Solaris

test1  
test2  
test3  
test4  
test5 

我想刪除包含test2的線,所以我用命令如下,但不是刪除只是「測試2 '將其刪除的整個文件和fize大小變成零。

bash# cat /aaa/bbb/ccc/myfile | sed -e '/test2/ d' > /aaa/bbb/ccc/myfile  
bash# ls -l total 0  
-rw-r--r-- 1 root  root   0 3月 11 17:41 myfile 

有人可以建議,命令有什麼不對嗎?

+1

我假設第一個'>'是一個錯字。重定向到文件'>/aaa/bbb/ccc/myfile'發生在文件被傳送到'sed'之前,所以文件被截斷,然後'cat'讀取一個空文件。如Venky的回答中所示使用臨時文件。 – 2011-03-14 07:53:46

+0

是第一個>是錯字,編輯。任何建議,使這項工作? – rupali 2011-03-14 08:57:58

回答

0

下面的代碼是workign爲我好...

touch myfile2 
cp /aaa/bbb/ccc/myfile myfile2 
sed '/test2/d' myfile2 > /aaa/bbb/ccc/myfile 
+2

沒有必要先觸摸文件。 – 2011-03-14 07:54:05

+0

我真的不想參與第二個文件..我可以只用myfile嗎?也在一行shell命令中? – rupali 2011-03-14 08:47:28

+0

這個工作嗎?
sed'/ test2/d'myfile>/aaa/bbb/ccc/myfile – rupali 2011-03-14 08:58:43

1

不幸的是,輸出重定向立即清空輸出文件。因此,您必須使用不同的文件作爲輸出文件,例如:

sed '/test2/d' /aaa/bbb/ccc/myfile > /aaa/bbb/ccc/myfile2 

或者您可以這樣的事情:

sed '/test2/d' /aaa/bbb/ccc/myfile | tee /aaa/bbb/ccc/myfile 

但由於緩衝這不是很可靠。如果輸出程序(tee)在sed完成讀取之前寫入文件,這將導致數據損壞。 也許你也可以使用程序buffermbuffer作爲tee的替代品,你可以指定緩衝區大小。但我在快速試用中沒有可靠的成功。

+0

sry但我不滿意這個答案,因爲你說它不可靠:( – rupali 2011-03-14 08:52:10

7

,除非你有GNU的sed(與「-i」選項),而你在Solaris上,所以你可能不這樣做,你沒有選擇,只能寫入臨時文件:

sed -e '.....' infile > infile.tmp 
mv infile.tmp infile 

更新:與ed

printf "%s\n" 'g/test2/d' w q | ed infile 
+2

「ed」即使沒有Gnu sed也可以完成這項工作 – jlliagre 2011-03-17 14:02:03

+0

@jlliagre,謝謝你的提示 – 2011-03-17 18:24:40

+0

然後隨意投我的答案。你的編碼是僞造的,應該是[printf「%s \ n%s \ n%s \ n」'g/test2/d'wq | ed infile]或者簡單地[printf'%s \ nw \ nq \ n 「'g/test2/d'| ed infile] – jlliagre 2011-03-17 22:14:14

1

編輯就地文件也可以使用grep

> grep -v test2 test.txt 
test1  
test3  
test4  
test5 

要注意的是,與sed,你不應該覆蓋你從閱讀文件,這樣你就可以調用它是這樣的:

的grep -v測試2的test.txt> test.out

+0

它只是顯示ou輸入沒有test2但實際test.txt沒有更新! – rupali 2011-03-14 11:27:35

5

我不知道perl是否在Solaris上是標準的。如果是這樣的話,你可以使用:

perl -ni -e 'if(!/test2/){print;}' myfile 
1

的Solaris,假設你是不是在一個古老的版本,應該已經配備了至少3的bash因此,使用bash的只是

while read -r line 
do 
    case "$line" in 
    *"test2"*) continue;; 
    *) echo "$line";; 
    esac 
done <file> temp && mv temp file 
0

你可以讀取整個文件到一個數組中AWK:

awk '!/test2/ {a[++c] = $0} END {for (i=1; i<=c; i++) print a[i] > FILENAME}' /aaa/bbb/ccc/myfile 

由於重定向無法外殼環境進行的,不進行早期截斷。

1

嘗試

grep -v test2 test.txt > temp 
mv temp test.txt 
2

您可以簡單地使用好老版:

echo "/test2 
d 
w 
q" | ed /aaa/bbb/ccc/myfile 
0
$touch myfile 

$printf "test1\ntest2\ntest3\ntest4\ntest5\n">myfile 

$cat myfile 

test1 
test2 
test3 
test4 
test5 

$sed '2d' myfile 

test1 
test3 
test4 
test5 

所以使用:

$sed '2d' myfile