Shell handles a file name with a space _linux shell

Source: Internet
Author: User
Tags echo name

Nowadays many people like to use spaces when they are named, such as "an Introduction.doc". But this naming problem is confusing to Linux command-line tools and shells, because most commands use whitespace as a separator between values and values, rather than as part of a filename.

Look at the script below, we can understand more clearly:

The results of the implementation are as follows:

In fact, there are only two files in the current directory:

For simple file names, as in the previous example, we can also get a list of files through a simple method such as for I-in *doc. But for the complex environment, how do we get these lists, as shown in the following diagram?

There is a way to get a list of file names through for i in "* *", but a bad list, because the result is a list of two file names together, and we simply can't take the next action, as shown in the following figure

The "*\ *" technique avoids the problems mentioned above, but there are problems when you apply MV or other actions.

The above question can be resolved by putting the variable in quotation marks ("$i"), and usually the spaces in the quotation marks can be handled correctly. But this is not a permanent solution because we can't deal with complex situations such as pipelines and sub shells.

An ultimate solution is to set up the IFS (the Internal Field Separator), do not use spaces as IFS, and choose other symbols. First Look at man page:

Ifs:the Internal Field Separator It used for word splitting after expansion and to split lines in words with the R EAD built-in command. The default value is "<space><tab><new-line>".

Another option is to replace the space with a special custom symbol before processing the file name, and then replace it at the end of the process.

Safename= "$ (echo name | sed ' s//_-_/g ')"

Original= "$ (echo $safename | sed s '/_-_//g ')"

Other methods, such as the Find command, are available.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.