开发者

Surround all lines in a text file with quotes ('something')

开发者 https://www.devze.com 2022-12-09 02:37 出处:网络
I\'ve got a list of directories that contain spaces. I need to surround them with \' \' to ensure that my batch scripts will work.

I've got a list of directories that contain spaces.

I need to surround them with ' ' to ensure that my batch scripts will work.

How can one su开发者_StackOverflow中文版rround each new line with a ' and a ' (quotes).

e.g.

File1:

/home/user/some type of file with spaces
/home/user/another type of file with spaces

To

File2:

'/home/user/some type of file with spaces'
'/home/user/another type of file with spaces'


Use sed?

sed -e "s/\(.*\)/'\1'/"

Or, as commented below, if the directories might contain apostrophes (nightmare if they do) use this alternate

sed -e "s/'/'\\\\''/g;s/\(.*\)/'\1'/"


Using sed:

sed -i "s/^.*$/'&'/g" filename


You can use sed(1) to insert single quotes at the beginning and end of each line in a file as so:

sed -i~ -e "s/^/'/;s/$/'/" the_file


I prefer awk (it's faster than bash and very easy to extend):

awk '{print "\'" $0 "\'"}'


very simple logic, you just need to echo the quotes in front and behind.

while read -r line
do
  echo "'$line'"
  # do something
done < "file"


Using sd, to surround with ' the command looks like:

sd '(.*)' \''$1'\'

to surround with " the command looks like:

sd '(.*)' '"$1"'

Hopefully you got the idea.

0

精彩评论

暂无评论...
验证码 换一张
取 消