UNIX:将具有不同扩展名的文件合并为一个文件

UNIX:将具有不同扩展名的文件合并为一个文件

例如:在我的 /temp 目录中,我有 100 个文件,其中 50 个扩展名为 .msg,另外 50 个扩展名为 .xml。

/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

相关内容