简体   繁体   English

在bash脚本中使用正则表达式

[英]Using regular expression in bash script

I'm new to bash scripting, but I want to do the following: 我是bash脚本的新手,但我想执行以下操作:

I want to detect the pattern STRING_1 "STRING_2" in FILE_1 and append STRING_2 to FILE_2 我想检测FILE_1中的模式STRING_1“ STRING_2”,并将STRING_2附加到FILE_2

what's a concise way to do this? 一种简单的方法可以做到这一点?

Your question is fairly vague; 您的问题相当模糊; but my guess at what you wanted 但是我猜你想要什么

if STRING_1 exists in FILE_1, append STRING_2 to FILE_2 如果FILE_1中存在STRING_1,则将STRING_2附加到FILE_2

answer=`grep -c STRING_1 FILE_1`
if [ "$answer" -gt 0 ] 
then
     echo "$STRING_2" >> FILE_2
fi

You could do something like: 您可以执行以下操作:

   sed 's/STRING_1 \"(.*)\"/\1/g' FILE_1 >FILE_2

What's happening here, is sed is searing for everything between the first and second '/' from FILE_1 and sending what's between the second and third '/' to FILE_2. sed在这里发生的事情是搜索FILE_1中第一个和第二个“ /”之间的所有内容,并将第二个和第三个“ /”之间的内容发送到FILE_2。

() groups are assigned to \\1, \\2, etc... so everything in between the \\"s are your STRING_2. ()组已分配给\\ 1,\\ 2等...,因此\\“之间的所有内容都是您的STRING_2。

grep -Po '(?<=aaa ")([^"]*)(?=")' FILE_1 >> FILE_2

If I understood correctly the question, and so you have a file containing: 如果我对问题的理解正确,那么您有一个包含以下内容的文件:

word1a "word1b"
word2a "word2b"
word3a "word3b"

You can use sed to extract the value contained between quotes, and then redirect to a file 您可以使用sed提取引号之间包含的值,然后重定向到文件

sed 's/.*"\(.*\)"/\1/' FILE_1 > FILE_2

You could also use this : 您也可以使用此:

grep '^\s*STRING_1\s*\".*\"\s*$' FILE_1 | awk -F \" '{printf $2"\n"}' >> FILE_2

It correctly handles multiple blank characters of the input file, and appends a newline after STRING_2 at the end of FILE_2. 它将正确处理输入文件的多个空白字符,并在FILE_2的末尾在STRING_2之后添加换行符。

This is what I have right now: 这就是我现在所拥有的:

sed 's/STRING_1\\s*:\\s*"([^"]*)"/\\1/g' "FILE_1" >> FILE_2; sed's / STRING_1 \\ s *:\\ s *“([^”] *)“ / \\ 1 / g'” FILE_1“ >> FILE_2;

I want it to detect the following pattern in file 1: 我希望它检测文件1中的以下模式:

STRING_1   :   "STRING_2"

and save STRING_2 to file 2 并将STRING_2保存到文件2

but this doesn't work, it appends a lot of random stuff to FILE_2(that are not supposed to match) 但这是行不通的,它会向FILE_2附加很多随机内容(不应该匹配)

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

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