|
藍森林 http://www.lslnet.com 2006年6月26日 11:18
請教:用sed實現文件分割功能
有file文本文件,如何將1-5行內容寫到文件 fhead,將末尾兩行內容寫到文件 ftail,其餘的中間部分寫到文件 fbody。用 sed 為主的 shell 如何實現?
謝謝! |
請教:用sed實現文件分割功能
關鍵是主文件的行數吧
#!/bin/sh
FileRow=`grep -c "^[a-zA-Z0-9]" video.txt`
FileRow=`expr $FileRow - 1`
echo $FileRow |
請教:用sed實現文件分割功能
[code]
n=$(cat tmp|wc -l)
awk 'NR<=5{print >"a.txt"};NR>5&&NR<'"$n"'-1{print >"b.txt"};NR>='"$n"'{print >"c.txt"}'[/code] |
請教:用sed實現文件分割功能
我對AWK不熟悉,曾經用了許多條SED命令實現:
flt=`cat file |wc -l |sed 's/ //g` #取文件總行數
fls=`expr $flt - 1` #取倒數第二行的行號
sed -n '1,5p' file >fhead
sed -n '${fls},${flt}p' file >ftail
sed '${fls},${flt}d 1,5d' <file >fbody #(具體格式記不清楚了)
但覺得太繁瑣,請問,有無更簡單的方法? |
請教:用sed實現文件分割功能
取文件總行數
flt=`cat file | wc -l`不可以嗎?為什麼後面還要加sed s'/ //g'呢? |
請教:用sed實現文件分割功能
sed -n '${fls},${flt}p' file >ftail
變量 ${fls} ${flt} 不能用呢? |
請教:用sed實現文件分割功能
回 bst:
應當是
sed -n "${fls},${flt}p" ...
經測試,應當用雙引號。 |
請教:用sed實現文件分割功能
回 fish617:
去掉前面的空格。 |
請教:用sed實現文件分割功能
終於改好一些了:
t1=`cat file |wc -l|sed 's/ //g'`
t2=`expr $t1 - 1`
sed -n "1,5w t.head
${t2},${t1}w t.tail
${t2},${t1}d
1,5d
w t.body
" <file
但還是覺得有一些繁瑣,不知各位有無更好的方案,更簡練一些。 |
請教:用sed實現文件分割功能
試試這個:
$cat filename
1 #include <sys/types.h>
2 #include <unistd.h>
3
4 int main(int argc, char **argv)
5 {
6 char ch = 0;
7
8 while (read(0, &ch, 1) == 1) {
9 if (ch < 0) {
10 if (read(0, &ch, 1) != 1)
11 break;
12 continue;
13 }
14 write(1, &ch, 1);
15 }
16 return 0;
17 }
程序如下:
nawk '{ line[NR] = $0 }
END { for(i = 1; i <= NR; i++){
if(i < 6)
print line[i] > "fhead"
if(i >= 6 && i <= NR - 2)
print line[i] > "fbody"
if( i > NR - 2)
print line[i] > "ftail" }
}' filename
運行結果:
$cat fhead
1 #include <sys/types.h>
2 #include <unistd.h>
3
4 int main(int argc, char **argv)
5 {
$cat fbody
6 char ch = 0;
7
8 while (read(0, &ch, 1) == 1) {
9 if (ch < 0) {
10 if (read(0, &ch, 1) != 1)
11 break;
12 continue;
13 }
14 write(1, &ch, 1);
15 }
$cat ftail
16 return 0;
17 } |
請教:用sed實現文件分割功能
[code]sed -n '1,5{
wt.head
b
}
6{
h
b
}
${
H
g
wt.tail
}
$!{
x
p
}' file >t.body[/code] |
| |