问题
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.
input:
projects.google.tests.inbox.document_01\r\nprojects.google.tests.inbox.document_02\r\nprojects.google.tests.inbox.global_02
Code:
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
Expected:
projects.google.tests.inbox.document_01
projects.google.tests.inbox.document_02
projects.google.tests.inbox.global_02
回答1:
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'
Output will be as follows.
projects.google.tests.inbox.document_01
projects.google.tests.inbox.document_02
projects.google.tests.inbox.global_02
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.
EDIT: 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
回答2:
inputData=$'projects.google.tests.inbox.document_01\r\nprojects.google.tests.inbox.document_02\r\nprojects.google.tests.inbox.global_02'
while IFS= read -r line; do
line=${line%$'\r'}
echo "$line"
done <<<"$inputData"
Note:
- The string is defined as
string=$'foo\r\n'
, notstring="foo\r\n"
. The latter does not put an actual CRLF sequence in your variable. See ANSI C-like strings on the bash-hackers' wiki for a description of this syntax. ${line%$'\r'}
is a parameter expansion which strips a literal carriage return off the end of the contents of the variableline
, should one exist.- The practice for reading an input stream line-by-line (used here) is described in detail in BashFAQ #1. Unlike iterating with
for
, it does not attempt to expand your data as globs.
来源:https://stackoverflow.com/questions/46556202/split-string-using-r-n-using-ifs-in-bash