简体   繁体   English

awk bash shell中的字符串替换

[英]String substitution in awk bash shell

cat filenames.txt
Document a.txt
Document b.txt
Document c.txt

Because I need to tar three files, so I use the command line 因为我需要压缩三个文件,所以我使用命令行

tar -cvzf backup.tar.gz "Document a.txt" "Document b.txt" "Document c.txt"

In order to do this: 为此:

cat filenames.txt | awk '{  how to add " "double quatation mark to file names}' | xargs tar -cvzf backup.tar.gz

Questions: 1.How to write code for awk {...}? 问题:1.如何为awk {...}编写代码? Thanks. 谢谢。

2.When () is included in the filename, why tar command cannot work? 2.当文件名中包含()时,为什么tar命令无法使用? How can I deal with special characters using tar? 如何使用tar处理特殊字符?

You can pass a file to the tar command using -T 您可以使用-T将文件传递给tar命令
It will then read the file and add all files inside that. 然后它将读取文件并在其中添加所有文件。

tar -cvzf backup.tar.gz -T filenames.txt

Example

$cat filenames.txt
Document a.txt
Document b.txt
Document c.txt

$tar -cvzf backup.tar.gz -T filenames.txt
Document a.txt
Document b.txt
Document c.txt

$tar -tvf backup.tar.gz
-rw-r--r-- me        4 2015-01-23 08:32 Document a.txt
-rw-r--r-- me        4 2015-01-23 08:32 Document b.txt
-rw-r--r-- me        4 2015-01-23 08:32 Document c.txt

Man page entry 手册页输入

-T, --files-from=FILE -T,--files-from = FILE
get names to extract or create from FILE 获取要从FILE提取或创建的名称

You can use xargs -I : 您可以使用xargs -I

cat filenames.txt | xargs -I {} tar -rvf backup.tar '{}'
gzip backup.tar

You could also use printf , if you need to use awk and the fileformat is specified/generated like STRING<SPACE>STRING.txt . 如果需要使用awk并且指定/生成的文件格式如STRING<SPACE>STRING.txt ,则也可以使用printf

awk '{ printf "\"%s %s\"\n", $1, $2 }' files.txt | xargs tar -cvzf backup.tgz

AWK is a great filter for processing generated rows and columns. AWK是用于处理生成的行和列的出色过滤器。

Since you don't need to filter the data, you could take the line as is. 由于不需要过滤数据,因此可以直接使用。

$ awk '{ printf "%s\n", $0; }' files.txt | xargs -I {} tar -rvf backup.tar {}
Document A.txt
Document B.txt

Or without printf (the whole line) 或不带printf(整行)

$ awk '{ print; }' files.txt | xargs -I {} tar -rvf backup.tar {}

and compress it in the last step, gzip can't update compressed archives: 并在最后一步进行压缩,gzip无法更新压缩档案:

$ gzip backup.tar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM