bash 使用“sed”从文件中获取子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8847718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get substring from file using "sed"
提问by Arthur Halma
Can anyone help me to get substring using sedprogram?
任何人都可以帮助我使用sed程序获取子字符串吗?
I have a file with this line:
我有一个包含这一行的文件:
....
define("BASE", "empty"); # there can be any string (not only "empty").
....
And I need to get "empty" as string variable to my bash script.
我需要将“空”作为字符串变量添加到我的 bash 脚本中。
At this moment I have:
此刻我有:
sed -n '/define(\"BASE\"/p' path/to/file.ext
# returns this line:
# define("BASE", "empty");
# but I need 'empty'
UPD:Thanks to @Jaypal
UPD:感谢@Jaypal
For now I have bash script:
现在我有 bash 脚本:
DBNAME=`sed -n '/define(\"BASE\"/p' path/to/file.ext`
echo $DBNAME | sed -r 's/.*"([a-zA-Z]+)".*//'
It work OK, but if there any way to make the same manipulation with one line of code?
它工作正常,但是有没有办法用一行代码进行相同的操作?
回答by ezdazuzena
You should use is
你应该使用是
sed -n 's/.*\".*\", \"\(.*\)\".*//p' yourFile.txt
which means something (.*
) followed by something in quotes (\".*\"
), then a comma and a blank space (,
), and then again something within quotes (\"\(.*\)\"
).
这意味着 ( .*
) 后跟引号 ( \".*\"
) 中的某些内容,然后是逗号和空格 ( ,
),然后又是引号 ( \"\(.*\)\"
) 中的某些内容。
The brackets define the part that you later can reuse, i.e. the string within the second quotes. used it with \1
.
括号定义您以后可以重用的部分,即第二个引号内的字符串。与\1
.
I put -n
front in order to answer the updated question, to get online the line that was manipulated.
我放在-n
前面是为了回答更新的问题,让被操纵的线路上线。
回答by jaypal singh
This should help -
这应该有帮助 -
sed -r 's/.*"([a-zA-Z]+)"\);//' path/to/file.ext
If you are ok with using awk
then you can try the following -
如果您可以使用,awk
那么您可以尝试以下操作 -
awk -F\" '/define\(/{print $(NF-1)}' path/to/file.ext
Update:
更新:
DBNAME=$(sed -r '/define\(\"BASE\"/s/.*"([a-zA-Z]+)"\);//' path/to/file.ext)
回答by Sidharth C. Nadhan
sed -nr '/^define.*"(.*)".*$/{s///;p}' path/to/file.ext
回答by Joey Baruch
if your file doesn't change over time (i.e. the line numbers will always be the same) you can take the line, and use delimiters to take your part out:
如果您的文件不随时间变化(即行号始终相同),您可以使用该行,并使用分隔符将您的部分去掉:
`sed -n 'Xp' your.file | cut -d ' ' -f 2 |cut -d "\"" -f 2`
assuming X is the line number of your required line
假设 X 是您所需行的行号