指定我的变量我没有什么问题.我有一个普通文本的文件,其中有一些括号[ ](整个文件中只有一对括号),以及它们之间的一些文本.我需要在shell(bash)变量中捕获这些括号内的文本.我该怎么办?
击/ sed的:
VARIABLE=$(tr -d '\n' filename | sed -n -e '/\[[^]]/s/^[^[]*\[\([^]]*\)].*$/\1/p')
Run Code Online (Sandbox Code Playgroud)
如果这是不可读的,这里有一点解释:
VARIABLE=`subexpression` Assigns the variable VARIABLE to the output of the subexpression.
tr -d '\n' filename Reads filename, deletes newline characters, and prints the result to sed's input
sed -n -e 'command' Executes the sed command without printing any lines
/\[[^]]/ Execute the command only on lines which contain [some text]
s/ Substitute
^[^[]* Match any non-[ text
\[ Match [
\([^]]*\) Match any non-] text into group 1
] Match ]
.*$ Match any text
/\1/ Replaces the line with group 1
p Prints the line
Run Code Online (Sandbox Code Playgroud)
我可以指出,虽然大多数建议的解决方案都可行,但绝对没有理由为什么要分叉另一个shell,并产生几个进程来完成这么简单的任务.
shell为您提供所需的所有工具:
$ var='foo[bar] pinch'
$ var=${var#*[}; var=${var%%]*}
$ echo "$var"
bar
Run Code Online (Sandbox Code Playgroud)