Awk

為什麼此命令僅適用於其他每一行?

  • August 10, 2018

當我跑步時\ls | xargs -I {} echo {} | sed 'N;s/\n/xxxxxxxxx/',我得到了這個:

- Books aliasxxxxxxxxxA New Kind of Science
Computability-and-Logic.pdfxxxxxxxxxComputability-and-Logic_k2opt.pdf
Hein J. L. - Prolog Experiments in Discrete Mathematics, Logic, and Computability (2005).pdfxxxxxxxxxHein J. L. - Prolog Experiments in Discrete Mathematics, Logic, and Computability (2005)_k2opt.pdf
How Automated Recommendations Affect the Playlist Creation Behavior of Users.pdfxxxxxxxxxHow Automated Recommendations Affect the Playlist Creation Behavior of Users_k2opt.pdf
Lumanote- A Real-Time Interactive Music Composition Assistant.pdfxxxxxxxxxgeMsearch- Personalized Explorative Music Search.pdf
research_report_dc_02.pdfxxxxxxxxxresearch_report_dc_02_k2opt.pdf
thebookofshaders.pdfxxxxxxxxxthebookofshaders_k2opt.pdf

我不明白為什麼輸出不是這樣:

- Books aliasxxxxxxxxxA New Kind of SciencexxxxxxxxxComputability-and-Logic.pdfxxxxxxxxxComputability-and-Logic_k2opt.pdfxxxxxxxxxHein J. L. - Prolog Experiments in Discrete Mathematics, Logic, and Computability (2005).pdfxxxxxxxxxHein J. L. - Prolog Experiments in Discrete Mathematics, Logic, and Computability (2005)_k2opt.pdfxxxxxxxxxHow Automated Recommendations Affect the Playlist Creation Behavior of Users.pdfxxxxxxxxxHow Automated Recommendations Affect the Playlist Creation Behavior of Users_k2opt.pdf
$ seq 10  | sed 'N;s/\n/+/'
1+2
3+4
5+6
7+8
9+10

N在模式空間中添加下一行,然後s用 連接這 2 行+,然後sed列印該行,並為下一行輸入重複腳本(其中第 3 行和第 4 行用+… 等連接)。

你需要

$ seq 10 | sed 'N;N;N;N;N;N;N;N;N;s/\n/+/g'
1+2+3+4+5+6+7+8+9+10

或在您的 sed 腳本中使用循環來連接所有行:

$ seq 10 | sed -e :1 -e '$!N;s/\n/+/;t1'
1+2+3+4+5+6+7+8+9+10

請注意,它將整個輸入吞入模式空間,這不能很好地擴展到大文件。

要使用一個字元分隔符連接行,您可以使用paste

$ seq 10 | paste -sd + -
1+2+3+4+5+6+7+8+9+10

對於不將整個輸入載入到記憶體中的多字元分隔符:

$ seq 10 | awk -v sep=-+- -vORS= 'NR>1 {print sep}; 1; END {if (NR) print RS}'
1-+-2-+-3-+-4-+-5-+-6-+-7-+-8-+-9-+-10

引用自:https://unix.stackexchange.com/questions/461826