指定变量几乎没有问题。我有一个带有普通文本的文件,并且在其中的某个位置有方括号[ ](整个文件中只有1对方括号),并且它们之间有一些文本。我需要在shell(bash)变量中的这些括号内捕获文本。请问我该怎么办?

最佳答案

重击/sed:

VARIABLE=$(tr -d '\n' filename | sed -n -e '/\[[^]]/s/^[^[]*\[\([^]]*\)].*$/\1/p')

如果无法理解,这里有一些解释:
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

09-10 05:28
查看更多