2012-10-15 47 views
1

可能重複:
Truncate stdin line length?打印前80個字符,在UNIX管道線

我一直在尋找一個awkperl(或者sed?)一內膽打印80行中的前80個字符用作:

cat myfile.txt | # awk/perl here 

我猜像perl -pe 'print $_[0..80]'應該工作,但我在perl不好。

編輯perl -pe 'print $_[0..80]不起作用,我不知道爲什麼。這就是我問這個問題的原因。我想解釋所有那些沉默downvotes ..

cat myfile.txt也只是爲了演示命令應該在一個管道中,我實際上使用一些其他輸出。

+0

你的意思是在每個*行嗎? – 2012-10-15 12:11:49

+0

@Tichodroma是 – none

+0

爲什麼這個下降? – none

回答

13

切:

cut -c1-80 your_file 

AWK:

awk '{print substr($0,0,80)}' your_file 

的sed:

sed -e 's/^\(.\{80\}\).*/\1/' your_file 

的Perl:

perl -lne 'print substr($_,0,80)' your_file 

或:

perl -lpe 's/.{80}\K.*//s' your_file 

的grep:

grep -o "^.\{80\}" your_file 
+0

不錯的答案idd,謝謝.. – none

+0

在你的perl解決方案中加入'-l'開關並移除'「\ n」'。你也可以使用'perl -plwe's。{0,80} \ K。* // s'' – TLP

+0

@steve ...好的一個:) – Vijay

2

使用cut,得到的第一個字符:如果你想在第一字節,使用

$ cut -c1-80 myfile.txt 

-b

$ cut -b1-80 myfile.txt 
1

用途如下:

$ cat myfile.txt | awk '{print substr($0,0,80)}'  

另一種方式是:

$ awk '{print substr($0,0,80)}' x 

這裏沒有必要的catawk可以從文件中讀取。

+0

不需要將'cat'文件轉換成'awk'。 – 2012-10-15 12:19:03

+0

@Tichodroma:爲什麼不呢?它需要NA ..我錯過了一些東西!.. –

+1

像'awk'這樣的所有工具都可以從文件中讀取。 – 2012-10-15 12:22:04

1

其中一種cut/sed/awk解決方案可能適合您,但您也可能對fold感興趣,因爲它可以讓您在字符數前面的空間換行和截斷,而不是在中間字字符數,如果你喜歡:

$ cat file 
the quick brown fox jumped over the lazy dog's back 

$ cat file | fold -w29 
the quick brown fox jumped ov 
er the lazy dog's back 

$ cat file | fold -s -w29 
the quick brown fox jumped 
over the lazy dog's back 

$ cat file | fold -w29 | head -1 
the quick brown fox jumped ov 

$ cat file | fold -s -w29 | head -1 
the quick brown fox jumped 

順便說一句,我是絕對不會用「貓」,如上圖所示,我假設OP還有其他一些命令寫到標準輸出,並只用「貓」到證明了這個問題。

+0

'fold'似乎很有用,但是'head -1'只返回第一行(對於多行輸出不起作用)。 – none

+0

和是順便說一句,我只是用'cat'來演示。我已編輯我的問題說,謝謝.. – none