我有一個檔案 foo.txt,有 2 行:
foo bar
hello world
我正在嘗試使用以下方法輸出第二行:
cut -d$'\n' -f2 foo.txt
但它正在列印兩行。
cut 是否能夠接受換行符作為分隔符?
uj5u.com熱心網友回復:
背景
cut 對輸入的所有行進行操作,因此我認為換行符不能用作分隔符。
從cut(1p)POSIX.1-2017 開始:
NAME cut - cut out selected fields of each line of a file SYNOPSIS cut -b list [-n] [file...] cut -c list [file...] cut -f list [-d delim] [-s] [file...] DESCRIPTION The cut utility shall cut out bytes (-b option), characters (-c option), or character-delimited fields ( -f option) from each line in one or more files, concatenate them, and write them to standard output.
例子:
$ printf 'foo bar1\nfoo bar2\n'
foo bar1
foo bar2
$ printf 'foo bar1\nfoo bar2\n' | cut -f 2 -d ' '
bar1
bar2
解決方案
只列印輸入的第二行,sed可以使用:
$ printf 'foo bar1\nfoo bar2\n'
foo bar1
foo bar2
$ printf 'foo bar1\nfoo bar2\n' | sed '2p;d'
foo bar2
uj5u.com熱心網友回復:
不太清楚您想要什么,但這是在空行上拆分并使用awk以下方法折疊其他行:
awk 'BEGIN {RS=""} {gsub("\n",""); print}'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359462.html
