Linux, how do I put double quotes around a file before linking it to tar?

I use ls to get my file name, which has a space, so it looks something like this:

my file with whitespace.tar.bz2

I want to associate this with a tar similar to:

 ls | grep mysearchstring | tar xvjf 

How to insert double quotes before binding it with tar?

+4
source share
2 answers

A good tool for this is search and xargs. For example, you can use:

 find . -name '*.tar.bz2' -print0 | xargs -0 -n1 tar xjf 

As a suggested pixelbeat, you can also use a wrapper as follows:

 for archive in *.tar.bz2; do tar xvjf "$archive"; done 
+7
source

What is wrong with shell expansion expansion? (Assuming there is only one file name.)

 % tar -cvf *mysearchstring* % tar -xvf *mysearchstring* 

Of course, a file name that matches * mysearchstring * will have spaces. But the shell [tcsh, bash] will assign this file name , including its spaces , to one tar argument.

You can verify this with a simple C or C ++ program. For instance:.

 #include <iostream> using namespace std; int main( int argc, char **argv ) { cout << "argc = " << argc << endl; for ( int i = 0; i < argc; i ++ ) cout << "argv[" << i << "] = \"" << argv[i] << "\"" << endl; return 0; } 

Try: ./a.out * foo *

This is why CSH has a parameter: q [quoted wordlist] ...

eg. [Tcsh]

 foreach FILE ( *mysearchstring* ) tar -xvf $FILE:q end 

Or tar -xvf "$ FILE" instead of tar -xvf $ FILE: q if you prefer.


If you really have to use ls ...

Using ls passed through anything yields one file name per line. Using tr, we can translate newlines to any other character, such as null. xargs can accept null-terminated strings. This circumvents the problem of spaces. Using -n1 will overcome the problem with multiple files.

For example: \ ls | grep mysearchstring | tr '\ 012' '\ 0' | xargs --null -n1 tar -xvf

But I don’t believe tar contains several tarfiles from stdin, as the OP does ...

0
source

All Articles