在bash中使用IFS使用\ r \ n分割字符串 [英] Split string using \r\n using IFS in bash
问题描述
我想在bash中拆分包含\ r \ n的字符串,但回车和\ n发出问题.谁能给我提示使用不同的IFS?我也尝试过IFS ='| \'.
I would like to split string contains \r\n in bash but carriage return and \n gives issue. Can anyone give me hint for different IFS? I tried IFS=' |\' too.
projects.google.tests.inbox.document_01\r\nprojects.google.tests.inbox.document_02\r\nprojects.google.tests.inbox.global_02
代码:
IFS=$'\r'
inputData="projects.google.tests.inbox.document_01\r\nprojects.google.tests.inbox.document_02\r\nprojects.google.tests.inbox.global_02"
for line1 in ${inputData}; do
line2=`echo "${line1}"`
echo ${line2} //Expected one by one entry
done
预期:
projects.google.tests.inbox.document_01
projects.google.tests.inbox.document_02
projects.google.tests.inbox.global_02
推荐答案
遵循awk可以帮助您解决问题.
Following awk could help you in your question.
awk '{gsub(/\\r\\n/,RS)} 1' Input_file
OR
echo "$var" | awk '{gsub(/\\r\\n/,RS)} 1'
输出如下.
projects.google.tests.inbox.document_01
projects.google.tests.inbox.document_02
projects.google.tests.inbox.global_02
说明: :使用awk
的gsub
实用程序(用于全局替换),其方法为gsub(/regex_to_be_subsituted/,variable/new_value,current_line/variable)
,因此在这里我给出\\
,这意味着它将把它当作文字字符)与当前行中的RS
(记录分隔符,其默认值为新行)一起使用.然后1
表示awk
使用条件和操作方法,因此提及1
时,我将条件设为TRUE,并且未给出任何操作,因此将发生当前操作的默认操作.
Explanation: Using awk
's gsub
utility which is used for globally substitution and it's method is gsub(/regex_to_be_subsituted/,variable/new_value,current_line/variable)
, so here I am giving \\r\\n
(point to be noted here I am escaping here \\
which means it will take it as a literal character) with RS
(record separator, whose default value is new line) in the current line. Then 1
means, awk
works on method of condition and action, so by mentioning 1
I am making condition as TRUE and no action is given, so default action print of current will happen.
使用变量,您可以按以下方式使用.
With a variable you could use as following.
var="projects.google.tests.inbox.document_01\r\nprojects.google.tests.inbox.document_02\r\nprojects.google.tests.inbox.global_02"
echo "$var" | awk '{gsub(/\\r\\n/,RS)} 1'
projects.google.tests.inbox.document_01
projects.google.tests.inbox.document_02
projects.google.tests.inbox.global_02
这篇关于在bash中使用IFS使用\ r \ n分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!