簡體   English   中英

UNIX中的子串

[英]Substring in UNIX

假設我有一個字符串“123456789”。

我想提取第3,第6和第8個元素。 我想我可以用

cut -3, -6, -8

但如果這樣的話

368

假設我想用白色空格分隔它們

3 6 8

我該怎么辦?

實際上shell參數擴展允許你直接進行子串切片,所以你可以這樣做:

x='123456789'
echo "${x:3:1}" "${x:6:1}" "${x:8:1}"

更新

要對整個文件執行此操作,請在循環中讀取該行:

while read x; do
  echo "${x:3:1}" "${x:6:1}" "${x:8:1}"
done < file

(順便說一句,bash切片是零索引的,所以如果你想要數字'3','6'和'8'你真的想要${x:2:1} ${x:5:1} and {$x:7:1} 。)

您可以使用sed工具並在您的終端中發出此命令:

sed -r "s/^..(.)..(.).(.).*$/\1 \2 \3/"

RegEx解釋: http//regex101.com/r/fH7zW6


要在文件上“概括”這個,你可以在像這樣的cat之后管道它:

cat file.txt|sed -r "s/^..(.)..(.).(.).*$/\1 \2 \3/"

Perl單線。

perl -lne '@A = split //; print "$A[2] $A[5] $A[7]"' file

使用cut

$ cat input
1234567890
2345678901
3456789012
4567890123
5678901234
$ cut -b3,6,8 --output-delimiter=" " input
3 6 8
4 7 9
5 8 0
6 9 1
7 0 2

-b選項僅選擇指定的字節。 可以使用--output-delimiter指定輸出--output-delimiter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM