我想替换括号中的单词以放入引号中。 我的previous question括号内有一个值。这个问题与我之前的问题相同,但想到了一种情况,我将在括号中包含多个值。
下面是我在变量数据之一中的数据 -
SELECT *
FROM (
SELECT table1 file2.txt file.txt queues qdefinitions parameters trap-deposit-dstran.dat.2016-08-07
FROM cs_case
WHERE ant_cd='FI_BASE_TENANT') t1
LEFT OUTER JOIN table2 t2
ON t2.case_id=t1.case_id
LEFT OUTER JOIN table3 t3
ON t3.service_xid=t1.service_xid
LEFT OUTER JOIN table4 t4
ON t4.service_id=t1.service_id
WHERE (
t1.casestatus_cd = (new,retired,pending,OPEN,closed)
OR t1.case_status_num = (1,2,3,4) )
GROUP BY t1.case_reference,
t2.last_scrfp,
t1.service_id
ORDER BY t2.last_scrfp DESC
这就是我想要的。
SELECT *
FROM (
SELECT table1 file2.txt file.txt queues qdefinitions parameters trap-deposit-dstran.dat.2016-08-07
FROM cs_case
WHERE ant_cd='FI_BASE_TENANT') t1
LEFT OUTER JOIN table2 t2
ON t2.case_id=t1.case_id
LEFT OUTER JOIN table3 t3
ON t3.service_xid=t1.service_xid
LEFT OUTER JOIN table4 t4
ON t4.service_id=t1.service_id
WHERE (
t1.casestatus_cd = ('NEW','RETIRED','PENDING','OPEN','CLOSED')
or t1.case_status_num = (1,2,3,4) )
GROUP BY t1.case_reference,
t2.last_scrfp,
t1.service_id
ORDER BY t2.last_scrfp DESC
以前我使用过 sed 命令如下
sed -E 's/\(([^(,$1)'\'']+)\)/('\''\1'\'')/g' Filename.txt
最佳答案
使用 solution由sln提供使用Regex Quote-Like operators ,提供可读性/可维护性。
加上一些编码,将它们组合在一起以适合您的特定场景:
use strict;
use warnings 'all';
# create a regex quote-like string for our match
my $rx = qr{\(([^)]+)\)};
# step through STDIN
while(<>) {
# Replace matching (...) sections by passing the matched part
# to QuoteText() and subsituting the result it returns.
#
# Note the 'e' and 'g' flags to s///, e enables "extended"
# operations which allows us to call QuoteText() and g
# replaces _all_ occurances on a line
s/$rx/QuoteText($1)/eg;
# print out the line (post any possible substitutions)
print;
}
sub QuoteText {
my $text = shift;
# the variable we will use to return our result
my $result;
# Does the text contain commas and also contains alphabetical characters?
if($text =~ /,/ && $text =~ /[a-z]/i) {
# split up the text around commas, then rejoin them with the
# string ',', and then prepend and append a single quote
# at the begining and end of line. So one,two becomes 'one','two'
$result = q/'/ . join(q/','/, split (',', $text)) . q/'/;
# The word _only_ contains numbers, spaces and commas, leave as is
} elsif($text =~ /^[\s\d,]+$/i) {
$result = $text;
# We possibly have just a single word? default to quoting the word
} else {
$result = qq/'$text'/;
}
# return our result wrapped in ()'s
return "($result)";
}
注意:我没有将引用的单词大写。如果您想实现这一目标,您将需要map
和uc
split
的部分。同样,在要引用的单词是数字和单词的混合的情况下,最终将引用所有数字和单词。如果这是一个问题,那么通过分割单词、循环每个单词、评估它的内容以查看它是否需要引用,然后将结果连接到返回的字符串可能会更好。
关于linux - 替换括号中的单词以放入引号中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38977424/