我需要合并兩個檔案,將檔案 2 的包含直接添加到檔案 1 的末尾。值得注意的是第一個檔案的最后一行包含短語“END”。我需要洗掉它并在那里添加檔案 2 的內容:
檔案 1:
string 1
string 2
string N
END
檔案 2:
string 3
string 4
string M
應該給我檔案 3
string 1
string 2
string N
string 3
string 4
string M
我試過簡單地使用
cat file1 file2 >> file3
但它沒有替換file2中的END。我可以為此使用特殊選項嗎?
uj5u.com熱心網友回復:
使用sed:
sed -e '${r file2' -e ';$d;}' file1
string 1
string 2
string N
string 3
string 4
string M
如果要直接使用shell變數而不是檔案名:
sed -i.bak -e "\${r $f2" -e ';$d;}' "$f1"
uj5u.com熱心網友回復:
一種方法awk。它只是!跳過END的最后一行發生的file1. file1它通過使用輔助變數來識別最后一行set。
在 a 中使用多個END進行測驗file
% awk 'set==""&&NR!=FNR&&last=="END"{last="";set=1}
last!=""{print last}
{last=$0} END{print}' file file
string 1
string 2
END
string N
string 1
string 2
END
string N
END
使用file1和file2
% awk 'set==""&&NR!=FNR&&last=="END"{last="";set=1}
last!=""{print last}
{last=$0} END{print}' file1 file2
string 1
string 2
string N
string 3
string 4
string M
資料
% cat file
string 1
string 2
END
string N
END
% cat file1
string 1
string 2
string N
END
% cat file2
string 3
string 4
string M
uj5u.com熱心網友回復:
這可能對你有用(GNU head & cat):
head -n-1 file1 | cat - file2 > file3
讀取除 file1 的最后一行之外的所有內容,并將其與 file2 連接。
替代:
sed -i -e '$r file2' -e '$d' file1
這會將 file2 附加到 file1 的末尾減去 file1 的最后一行,然后用結果替換 file1。
uj5u.com熱心網友回復:
在此處添加 1 個tac awk解決方案變體以獲得樂趣。
tac file1 | awk 'FNR==1{system("tac file2");next} 1' | tac
說明:為上述添加詳細說明。
tac file1 | ##using tac command to read contents from bottom to up and sending its standard output as standard input to awk command here.
awk ' ##Starting awk program from here.
FNR==1{ ##Checking condition if this is first line then do following.
system("tac file2") ##Printing file2 bottom to up contents.
next ##next will skip all further contents from here.
}
1 ##Printing rest of lines(passed from tac file1) here.
' | tac ##Reversing order again to make it into original order.
uj5u.com熱心網友回復:
假設:
file1只有一個條目被標記END- 條目位于
END末尾file1
對 OP 當前想法的小修改,cat使用程序替換來剝離ENDfrom file1:
$ cat <(grep -v '^END$' file1) file2 > file3
$ cat file3
string 1
string 2
string N
string 3
string 4
string M
安德烈awk解決方案的一種變體,我們列印除了file1/END條目之外的所有內容:
$ awk 'FNR==NR && /^END$/ {next} 1' file1 file2 > file3
$ cat file3
string 1
string 2
string N
string 3
string 4
string M
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/410598.html
標籤:
