简体   繁体   English

bash:处理奇怪的文件名尾部无效选项-1

[英]bash: dealing with strange filenames tail invalid option --1

I want my script to find a file (in the current directory) with the first line equal to START . 我希望我的脚本找到第一行等于START的文件(在当前目录中)。 Then that file should have FILE <file_name> as the last line. 然后,该文件的最后一行应为FILE <file_name> So I want to extract the <file_name> - I use tail for this. 所以我想提取<file_name> -为此我使用tail It works ok for standard file names but cracks for nonstandard file names like aa or a+bc\\ = e with tail reporting tail option used in invalid context -- 1 对于标准文件名它可以正常工作,但对于非标准文件名(如aaa+bc\\ = e可以破解,并且tail option used in invalid context -- 1 tail报告tail option used in invalid context -- 1

Here is the beginning of the script: 这是脚本的开头:

#!/bin/bash

next_stop=0;

# find the first file
start_file=$(find . -type f -exec sed '/START/F;Q' {} \;)
mv "$start_file" $start_file       # << that trick doesn't work

if [ ! -f "$start_file" ]
then
  echo "File with 'START' head not found."
  exit 1
else
    echo "Found $start_file"
fi

# parse the last line of the start file
last_line=$(tail -1 $start_file)    # << here it crashes for hacky names
echo "last line: $last_line"
if [[ $last_line == FILE* ]] ; then 
    next_file=${last_line#* }
    echo "next file from last line: $next_file"
elif [[ $last_line == STOP ]] ; then
        next_stop=true;
    else
        echo "No match for either FILE or STOP => exit"
        exit 1
    fi

I tried to embrace the find output with braces this way 我试图用大括号将find输出包含在内

mv "$start_file" $start_file

but it doesn't help 但这没有帮助

For you two examples, you need to escape space and egual in file name (with \\ character), and escape escape character too. 对于两个示例,您需要转义文件名中的空格和等号(带有\\字符),并且也转义转义字符。 So aa have to be a\\ a when passing to tail, and a+bc\\ = e have to be a+bc\\\\\\ \\=\\ e . 因此, aa传递到尾部时必须为a\\ a ,而a+bc\\ = e必须为a+bc\\\\\\ \\=\\ e You can use sed to make this replacement. 您可以使用sed进行此替换。

This example give you an better and easier way to make this replacement : 本示例为您提供了一种更好,更轻松的替代方法:

printf '%q' "$Strange_filename"

This error is occur to the character of the escape. 转义符出现此错误。 You should write it start_file variable in quotes. 您应该将其start_file变量用引号引起来。 last_line=$(tail -1 $start_file) --> last_line=$(tail -1 "$start_file") last_line = $(tail -1 $ start_file)-> last_line = $(tail -1“ $ start_file”)

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

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