从双引号bash脚本中包含的字符串中删除空格

use*_*781 3 unix string bash awk

我一直在使用sep来尝试这个,基本上我有一个文本文件,其中包含相同数量的相同行,例如

4444 username "some information" "someotherinformation" "even more information"
Run Code Online (Sandbox Code Playgroud)

我需要用下划线替换引号内的空格,所以它看起来像这样

4444 username "some_information" "someotherinformation" "even_more_information"
Run Code Online (Sandbox Code Playgroud)

目前我已经能够分离出引用的信息

sed 's/"\([^"]*\)"/_/g' myfile.txt
Run Code Online (Sandbox Code Playgroud)

关于如何进行的建议?

Pau*_*ce. 6

sed -r ':a; s/^((([^"]*"){2})*[^"]*"[^" ]*) /\1_/;ta'
4444 username "some_information" "someotherinformation" "even_more_information"
Run Code Online (Sandbox Code Playgroud)

要么

sed ':a; s/^\(\(\([^"]*"\)\{2\}\)*[^"]*"[^" ]*\) /\1_/;ta'
4444 username "some_information" "someotherinformation" "even_more_information"
Run Code Online (Sandbox Code Playgroud)
  • :a - 为循环标记"a"
  • s/// - 进行替换
  • ^( - 将整个搜索字符串锚定在行的开头
  • (([^"]*"){2})* - 捕获(在第1组中)两组零个或多个非引号,后跟一个引号(零次或多次)
  • [^"]*" - 后跟零或多个非报价,后跟报价
  • [^" ]* - 后跟零个或多个不是空格或引号的字符
  • ) - 结束锚定序列并寻找替换所需的空间
  • \1 - 用匹配序列替换捕获的组和下划线
  • ta- 分支(传输执行)标记:a是否已成功完成替换(如果没有,则继续执行下一条指令 - 在这种情况下,结束此行的处理并读取下一行,开始新一轮处理)

这将找到最后一个带引号的字符串中的第一个空格,该空格具有任何空格并替换它.然后是下一个,如果有的话,直到引用的字符串结束.等等任何额外的空间.

然后是包含空格的下一个前一个带引号的字符串......依此类推.

这是通过:a... ta循环的每一步的模式空间:

4444 username "some information" "someotherinformation" "even_more information"

4444 username "some information" "someotherinformation" "even_more_information"

4444 username "some_information" "someotherinformation" "even_more_information"
Run Code Online (Sandbox Code Playgroud)

然后它会再次走几步,在线的开头寻找任何匹配.