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

旧巷老猫 提交于 2019-12-20 08:36:11

问题


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 surround 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'

回答1:


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'/"



回答2:


Using sed:

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



回答3:


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



回答4:


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"


来源:https://stackoverflow.com/questions/1616577/surround-all-lines-in-a-text-file-with-quotes-something

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!