UNIX:將不同副檔名的檔案合併為一個文件

UNIX:將不同副檔名的檔案合併為一個文件

例如:在我的 /temp 目錄中,有 100 個檔案。

/temp/test1.xml
/temp/test2.xml
/temp/test3.xml
.........
/temp/test49.xml
/temp/test50.xml

/temp/test1.msg
/temp/test2.msg
/temp/test3.msg
.........
/temp/test49.msg
/temp/test50.msg

在文字檔案中,我想依序輸出 .xml 和 .msg 檔案內容的組合。例如,輸出檔案應如下所示:

content of test1.xml
content of test1.msg
content of test2.xml
content of test2.msg
content of test3.xml
content of test3.msg
............
content of test49.xml
content of test49.msg
content of test50.xml
content of test50.msg

在此 /temp 目錄中總是有相同數量的 .msg 和 .xml 檔案。另外,是否可以在輸出檔案的內容之前顯示路徑或檔案名稱?例如:

text1.xml: content of test1.xml 
text1.msg: content of test1.msg
text2.xml: content of test2.xml
text2.msg: content of test2.msg
text3.xml: content of test3.xml
text3.msg: content of test3.msg
....................
text49.xml: content of test49.xml
text49.msg: content of test49.msg
text50.xml: content of test50.xml
text50.msg: content of test50.msg

我嘗試過一個簡單的管道來歸檔

cat * > text.txt

但這並沒有給出所需的結果。在輸出檔案中,它首先列出所有 *.xml 檔案的內容,然後列出 *.msg 檔案。

請協助。

答案1

for f in *xml ; do
  cat "$f" "${f/.xml/.msg}"
done > OUTPUTFILE

如果您使用的是 shell,可能對您有用bash。否則(其他 POSIX shell)使用:cat "$f" "${f%.xml}.msg"代替上面的cat行。

答案2

在這種情況下,按以下步驟進行通常是有意義的:

  1. 將所有文件列出到一個文字文件中:

    $ ls > files
    
  2. 編輯文字文件,刪除不需要的文件並將剩餘文件按照您想要的順序排列。

  3. 然後就這樣做(假設所有檔案的名稱中都沒有空格或有趣的字元):

    $ cat $(cat files) > bigfile
    

這種方法的變體是將文字檔案更改為一個大命令,從

file1
file2
file with spaces 3
...
filen

到:

cat \
file1 \
file2 \
"file with spaces 3" \
... \
filen \
> bigfile

然後將文件作為腳本來源:

$ . ./files

vi使用時可以將空格和反斜線新增到緩衝區中的每一行:%s/$/ \\/

答案3

for i in {1..50}; do
    echo "text$i.xml: `cat text$i.xml`" >> output.txt
    echo "text$i.msg: `cat text$i.msg`" >> output.txt
done

答案4

如果是正常序列你可以這樣做:

在bash中:

for ITER in {1..50}
do
    cat test${ITER}.xml
    cat test${ITER}.msg
done > test.txt

或者如果你有實用程式seq

for ITER in $(seq 1 50)
do
    cat test${ITER}.xml
    cat test${ITER}.msg
done > test.txt

相關內容