简体   繁体   中英

Bash script to enclose words in single quotes

I'm trying to write a bash script to enclose words contained in a file with single quotes.

Word - Hello089

Result - 'Hello089',

I tried the following regex but it doesn't work. This works in Notepad++ with find and replace. I'm not sure how to tweak it to make it work in bash scripting.

sed "s/(.+)/'$1',/g" file.txt > result.txt

Replacement backreferences (also called placeholders) are defined with \n syntax, not $n (this is perl-like backreference syntax).

Note you do not need groups here, though, since you want to wrap the whole lines with single quotation marks. This is also why you do not need the g flags, they are only necessary when you plan to find multiple matches on the same line , input string.

You can use the following POSIX BRE and ERE (the one with -E ) solutions:

sed "s/..*/'&',/" file.txt > result.txt
sed  -E "s/.+/'&',/" file.txt > result.txt

In the POSIX BRE (first) solution, ..* matches any char and then any 0 or more chars (thus emulating .+ common PCRE pattern). The POSIX ERE (second) solution uses .+ pattern to do the same. The & in the right-hand side is used to insert the whole match (aka \0 ). Certainly, you may enclose the whole match with capturing parentheses and then use \1 , but that is redundant:

sed "s/\(..*\)/'\1',/" file.txt > result.txt
sed  -E "s/(.+)/'\1',/" file.txt > result.txt

See the escaping, capturing parentheses in POSIX BRE must be escaped.

See the online sed demo .

s="Hello089";
sed "s/..*/'&',/" <<< "$s"
# => 'Hello089',
sed -E "s/.+/'&',/" <<< "$s"
# => 'Hello089',

$1 is expanded by the shell before sed sees it, but it's the wrong back reference anyway. You need \1 . You also need to escape the parentheses that define the capture group. Because the sed script is enclosed in double quotes, you'll need to escape all the backslashes.

$ echo "Hello089" | sed "s/\\(.*\\)/'\1',/g"
'Hello089',

(I don't recall if there is a way to specify single quotes using an ASCII code instead of a literal ' , which would allow you to use single quotes around the script.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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